array_map with anonymous function vs convoluted example

Submitted by darraghenright on Thu, 06/07/2012 - 10:16

f1 is slower than f2 by 65.55%

Full source code as executed.
/* How many times the code under test should run in each function */
define('LOOP', 100000);
define('MAX', 10);
 
function f1() 
{
    for ($i = 0; $i < LOOP; ++$i) {
        // one liner array_map with anonymous function - 5.3+
        $array = array_map(function($d) { return 'count_' . $d; }, range(0, MAX));
    }
}
function f2()
{
    for ($i = 0; $i < LOOP; ++$i) {
        // another (convoluted) one line approach, avoiding array_map - 5.2+
        $array = explode('#', 'count_' . implode('#count_', range(0, MAX)));
    }
}
$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.26%294213716412655.3.3-7+squeeze1
62.6%375180230733php-5.3.6-phpbrew_compiled
73.06%394441227923php-5.3.7-phpbrew_compiled
82.68%415541227465php-5.3.8-phpbrew_compiled
59.08%363408228448php-5.3.9-phpbrew_compiled
59.65%364447228282php-5.3.10-phpbrew_compiled
61.63%368906228240php-5.3.11-phpbrew_compiled
61.81%376628232758php-5.3.12-phpbrew_compiled
61.61%368888228254php-5.3.13-phpbrew_compiled
54.52%358740232160php-5.3.14-phpbrew_compiled
60.87%372094231303php-5.3.15-phpbrew_compiled
61.77%371609229711php-5.3.16-phpbrew_compiled
59.75%371649232648php-5.3.17-phpbrew_compiled
59.26%376669236508php-5.3.18-phpbrew_compiled
53.4%366391238849php-5.3.19-phpbrew_compiled
75.32%362986207042php-5.4.0-phpbrew_compiled
66.8%355900213370php-5.4.1-phpbrew_compiled
61.92%369580228254php-5.4.2-phpbrew_compiled
67.36%357010213317php-5.4.3-phpbrew_compiled
66.03%351920211960php-5.4.4-phpbrew_compiled
71.88%361005210037php-5.4.5-phpbrew_compiled
71.12%361020210973php-5.4.6-phpbrew_compiled
69.43%354752209378php-5.4.7-phpbrew_compiled
68.49%363021215454php-5.4.8-phpbrew_compiled
69.47%358243211395php-5.4.9-phpbrew_compiled
50%
updown
50%