array_merge vs foreach (with numeric keys)

Submitted by Lito on Wed, 08/08/2012 - 13:21

f1 is slower than f2 by 85.06%

Full source code as executed.
/* How many times the code under test should run in each function */
define('LOOP',100000);
function f1() {
  $allvalues = range(0, LOOP);
  $morevalues = range(0, LOOP);
 
  $allvalues = array_merge($allvalues, $morevalues);
}
function f2() {
  $allvalues = range(0, LOOP);
  $morevalues = range(0, LOOP);
 
  foreach ($morevalues as $value) {
    $allvalues[] = $value;
  }
}
$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
79.31%4368872436505.3.3-7+squeeze1
101.71%6550832476php-5.3.6-phpbrew_compiled
106.8%6615431990php-5.3.7-phpbrew_compiled
106.38%6629232122php-5.3.8-phpbrew_compiled
99.11%6418032233php-5.3.9-phpbrew_compiled
97.97%6290631775php-5.3.10-phpbrew_compiled
98.33%6359432065php-5.3.11-phpbrew_compiled
97.92%6319131928php-5.3.12-phpbrew_compiled
104.14%6506631873php-5.3.13-phpbrew_compiled
98.56%6267631565php-5.3.14-phpbrew_compiled
96.72%6362732344php-5.3.15-phpbrew_compiled
101.15%6736233489php-5.3.16-phpbrew_compiled
99.77%6341431744php-5.3.17-phpbrew_compiled
97.13%6304131980php-5.3.18-phpbrew_compiled
99.26%6372831982php-5.3.19-phpbrew_compiled
60.86%6651941352php-5.4.0-phpbrew_compiled
66.22%6883241410php-5.4.1-phpbrew_compiled
69.26%7188842472php-5.4.2-phpbrew_compiled
66.8%7117942674php-5.4.3-phpbrew_compiled
60.23%6638741433php-5.4.4-phpbrew_compiled
59.6%6575041197php-5.4.5-phpbrew_compiled
65.93%6768640791php-5.4.6-phpbrew_compiled
66.72%6857841134php-5.4.7-phpbrew_compiled
66.31%6800340889php-5.4.8-phpbrew_compiled
60.36%6473240367php-5.4.9-phpbrew_compiled
100%
updown
0%