Inside foreach: access to copied value vs access to the original array

Submitted by Hani on Wed, 06/01/2011 - 21:26

f2 is slower than f1 by 36.07%

Full source code as executed.
/* How many times the code under test should run in each function */
define('LOOP',10000);
$a = array_fill(0,1000,17);
function f1() {
  global $a;
  for($i=0; $i<LOOP; ++$i) {
    foreach($a as $k => $v) { $v; }
  }
}
function f2() {
  global $a;
  for($i=0; $i<LOOP; ++$i) {
    foreach($a as $k => $v) { $a[$k]; }
  }
}
$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
25.94%213472626884095.3.3-7+squeeze1
32.44%375104496801php-5.3.6-phpbrew_compiled
27.96%379258485299php-5.3.7-phpbrew_compiled
30.51%368682481149php-5.3.8-phpbrew_compiled
25.13%378931474165php-5.3.9-phpbrew_compiled
27.89%377941483362php-5.3.10-phpbrew_compiled
29.31%371291480133php-5.3.11-phpbrew_compiled
29.27%374227483754php-5.3.12-phpbrew_compiled
29.34%371363480318php-5.3.13-phpbrew_compiled
29.45%365344472950php-5.3.14-phpbrew_compiled
28.74%371407478142php-5.3.15-phpbrew_compiled
19.03%513972611773php-5.3.16-phpbrew_compiled
28.07%378644484943php-5.3.17-phpbrew_compiled
28.52%366888471518php-5.3.18-phpbrew_compiled
28.36%369652474485php-5.3.19-phpbrew_compiled
48.03%320036473763php-5.4.0-phpbrew_compiled
46.69%315770463215php-5.4.1-phpbrew_compiled
46.7%315440462744php-5.4.2-phpbrew_compiled
46.93%318300467669php-5.4.3-phpbrew_compiled
46.81%316908465266php-5.4.4-phpbrew_compiled
47.21%309154455106php-5.4.5-phpbrew_compiled
50.78%309645466879php-5.4.6-phpbrew_compiled
49.1%310632463149php-5.4.7-phpbrew_compiled
49.03%307566458371php-5.4.8-phpbrew_compiled
50.54%313772472353php-5.4.9-phpbrew_compiled
50%
updown
50%