Access to global vs local variable

Submitted by tomek on Sun, 05/08/2011 - 13:44

f2 is slower than f1 by 1.13%

Full source code as executed.
define('LOOP',10000000);
 
$global = "Test string 123";
 
function f1() {
  global $global;
  for($i=0; $i<LOOP; ++$i) {
    $global = "a";
  }
}
 
function f2() {
  $local = "Test string 123";
  for($i=0; $i<LOOP; ++$i) {
    $local = "a";
  }
}
 
$start = microtime(true);
f1();
$stop = microtime(true);
$time1 = $stop - $start;
 
$start = microtime(true);
f2();
$stop = microtime(true);
$time2 = $stop - $start;
 
echo $time1 . "\t";
echo $time2 . "\n";
Test results
comparisontime1time2php_version
1.78%540549155017755.3.5-1ubuntu7.2
8.28%526458657004695.3.3-7
0.06%824400082490375.3.5-1ubuntu7.2
3.17%500386651624935.3.3-7+squeeze1
4.69%695729728384php-5.3.6-phpbrew_compiled
0.61%698960703228php-5.3.7-phpbrew_compiled
1%703486710507php-5.3.8-phpbrew_compiled
1.17%764218755363php-5.3.9-phpbrew_compiled
1.82%720952734102php-5.3.10-phpbrew_compiled
3.1%692881714359php-5.3.11-phpbrew_compiled
2.83%693050712654php-5.3.12-phpbrew_compiled
3.52%699903724548php-5.3.13-phpbrew_compiled
2.99%705737726829php-5.3.14-phpbrew_compiled
0.51%705664709267php-5.3.15-phpbrew_compiled
1.16%704202712385php-5.3.16-phpbrew_compiled
3.58%725100751033php-5.3.17-phpbrew_compiled
5.15%716691753626php-5.3.18-phpbrew_compiled
5.13%705370741556php-5.3.19-phpbrew_compiled
0.88%318509315730php-5.4.0-phpbrew_compiled
3.32%447755433388php-5.4.1-phpbrew_compiled
0.74%371411368685php-5.4.2-phpbrew_compiled
3.32%463566448679php-5.4.3-phpbrew_compiled
0.83%323484320808php-5.4.4-phpbrew_compiled
1.11%318468314974php-5.4.5-phpbrew_compiled
0.72%318161315892php-5.4.6-phpbrew_compiled
1.32%318837314688php-5.4.7-phpbrew_compiled
1.76%321348315796php-5.4.8-phpbrew_compiled
2.53%460175448815php-5.4.9-phpbrew_compiled
50%
updown
50%