I'Ve made a few test on global vs function parameter and the difference is futile.
But as i was testing stuff, i found that $GLOBALS is about 10% slower. than using function parameter or global keyword. Anyone care to explain why?
I wish to understand further the mechanism behind PHP. This so i can make better compromise on futur dev. Not that i ever use $GLOBALS except in some exception case.
$md5 = md5(1000000);
function byGlobal() {
global $md5;
$c = 0;
while( md5($c) != $md5 ){
$c++;
}
}
function superGlobal() {
$c = 0;
while( md5($c) != $GLOBALS[ 'md5' ] ){
$c++;
}
}
function asParam($md5) {
$c = 0;
while( md5($c) != $md5 ){
$c++;
}
}
$time3 = microtime(true);
asParam($md5);
echo (microtime(true) - $time3);
echo "<br/>";
$time1 = microtime(true);
byGlobal();
echo (microtime(true) - $time1);
echo "<br/>";
$time2 = microtime(true);
superGlobal();
echo (microtime(true) - $time2);
echo "<br/>";
I'm not arguing about function vs global or good practice. I really just wonder why so much difference. Ran the test 20 times and results are pretty much all consistent.
- i move the calls up and down in the code to avoid caching influence.
- I'm doing a million md5 iteration on each call so the server works a load.
- Time results are cosistent with other hashing function (tested sha1, crc32) and they are all in the same +10% slower)
- Ran on a VM with PHP 5.4.16 on CentOs7.
1st run
as param : 0.8601s
as global : 0.8262s
as $GLOBALS : 0.9463s (more than 10% slower)
2nd run
as param : 0.8100s
as global : 0.8058s
as $GLOBALS : 0.9624s (more than 10% slower again)
Related studies : (mainely debate about global best practice, nothing about $GLOBALS vs global performance.
The advantage / disadvantage between global variables and function parameters in PHP?