Part 1 - Static methods vs static variables vs class constants in php


Lets say you have an array of data which is static, where do you put it ?

There are several places you can put it

1. Static variables ( which can be altered at run time )

2. Class constants ( which cant be altered at run time )

3. Static methods ( array constructed at run time )

 

so i decided to benchmark these stuff.  At the moment i didnt knew about initialization cost of the array ( static method). I chose a json data of 25 MB which will be converted to array. 

 

Static Method

 

echo memory_get_usage(true) ."\n";
require_once "foo1.php";
echo memory_get_usage(true) ."\n";

Foo::benchmark(array('Foo', 'bar'));
Foo::benchmark(array('Foo', 'bar'));
Foo::benchmark(array('Foo', 'bar'));
Foo::benchmark(array('Foo', 'bar'));
Foo::benchmark(array('Foo', 'bar'));

echo memory_get_usage(true) ."\n";


The time required to initialize the 25 mb json array.

1.9073486328125E-6
0
0
0
0


Notice there is no initialization cost after first call. The memory usage details are

2097152    <-  at first list before everything is loaded
182452224  <- After class file loaded
182452224  <-  After 5 calls


I will check the static variables and class constants in next few days


Share:

0 comments:

Post a Comment