Part 2 - Static methods vs static variables vs class constants benchmarking

 In the part 1 we did a performance test on static methods and found that even though the method is not invoked it was using 182 MB of memory. The array was hardcoded in to the class. In this part we will benchmark the usage of static variables and see if it makes any difference in terms of performance.

So i placed the big data inside the static variable, so i got these results

<?php
echo memory_get_usage(true) ."\n";
require_once "static_variable.php";
echo memory_get_usage(true) ."\n";


2097152  <- before loading the file
182452224 <- after loading the file ( ~182 MB)

As you can see these are the same values as the static method. So we can safely conclude that both static methods and variables dont have any difference in terms of memory usage.

 

Now lets go to the other case, class constants. i created the file with large data for class constants.

<?php
echo memory_get_usage(true) ."\n";
require_once "class_constant.php";
echo memory_get_usage(true) ."\n";

This gave the same result.

2097152  <- before loading the file
182452224 <- after loading the file ( ~182 MB)

 I was curious to know what will happen if i create multiple objects from the class.so i did these

 

<?php
echo memory_get_usage(true) ."\n";
require_once "class_constant.php";
$f1 = new Foo();
$f2 = new Foo();
$f3 = new Foo();
echo memory_get_usage(true) ."\n";





This gave the same result.

2097152  <- before loading the file
182452224 <- after loading the file ( ~182 MB)

 

To conclude if you have large data it doesnt make any difference to static method, static variable or class constant. But conceptually its correct to use class constants unless you are performing mutations on the data in the program. 

i have added my code to this repo, so that you can perform these tests yourself

https://github.com/naveen17797/php-performance-benchmark

 

 


Share:

0 comments:

Post a Comment