I want to measure the exact loading time of a bunch of constants in php files. I've chosen 4 methods:
- using a key-value pair array (return an array of data in php file)
- using a class with constants in it
- define
- json (write json_encoded values into a file and the load them using a file_get_contents and json_decode)
First I created 4 different files with these methods and then filled them with 5000 random name and value pairs (same values for all).
I tried to load them in PHP and used microtime
function to measure the time of loading but the results seems a bit strange! This is my test.php
file:
// array
$time['array']['start'] = microtime(true);
$config_a = include('conf_array.php');
$time['array']['end'] = microtime(true);
// class
$time['class']['start'] = microtime(true);
include('conf_class.php');
$config_c = new Config();
$time['class']['end'] = microtime(true);
// define
$time['defin']['start'] = microtime(true);
include('conf_define.php');
$time['defin']['end'] = microtime(true);
// json
$time['json']['start'] = microtime(true);
$config_j = json_decode(file_get_contents('conf_json.json'));
$time['json']['end'] = microtime(true);
foreach ($time as $name => $item) {
echo $name . ": " . (($item['end'] - $item['start']) * 1000) . " units.";
}
When I load the test.php
with a set of new generated files, I'll get these results:
Array: 7.9629421234131 units.
Class: 6.5279006958008 units.
Defin: 19.877910614014 units.
Json: 4.4741630554199 units.
but when I hit refresh button (F5), the results will change! Here are the results of the same sample after refreshing the page:
Array: 1.7659664154053 units.
Class: 2.467155456543 units.
Defin: 6.4060688018799 units.
Json: 4.9409866333008 units.
And then, the order wont change anymore. It seems that php files (all except json) will load faster when you load them more than once. The same thing will happen if I restart apache (along with PHP).
I was wondering why is this happening?! Does it have something to do with some kind of caching?