closure vs. create_function

pholden's picture
Submitted by pholden on Tue, 11/13/2012 - 11:16

f2 is slower than f1 by 104.93% (1 times slower)

Full source code as executed.
/* How many times the code under test should run in each function */
define('LOOP',10000);
define('MAX', 100);
 
$a = range(0, MAX);
 
function f1() {
    global $a;
 
    for($i = 0; $i < LOOP; ++$i) {
        $callback = function($n) { return pow($n, 2); };
        array_map($callback, $a);
    }
}
 
function f2() {
    global $a;
 
    for($i = 0; $i < LOOP; ++$i) {
        $callback = create_function('$n', 'return pow($n, 2);');
        array_map($callback, $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
40.04%215906430234545.3.3-7+squeeze1
113.32%286020610145php-5.3.6-phpbrew_compiled
115.88%286342618150php-5.3.7-phpbrew_compiled
113.42%288781616307php-5.3.8-phpbrew_compiled
112.97%288184613736php-5.3.9-phpbrew_compiled
115.54%282621609165php-5.3.10-phpbrew_compiled
114.07%285583611344php-5.3.11-phpbrew_compiled
114.65%285612613052php-5.3.12-phpbrew_compiled
113.77%286240611881php-5.3.13-phpbrew_compiled
116.06%286281618538php-5.3.14-phpbrew_compiled
113.89%291129622684php-5.3.15-phpbrew_compiled
113.2%289744617723php-5.3.16-phpbrew_compiled
113.71%286908613165php-5.3.17-phpbrew_compiled
113.69%286322611839php-5.3.18-phpbrew_compiled
115.44%283673611144php-5.3.19-phpbrew_compiled
99.41%263663525763php-5.4.0-phpbrew_compiled
97.52%265414524246php-5.4.1-phpbrew_compiled
99.59%275170549201php-5.4.2-phpbrew_compiled
97.36%266344525659php-5.4.3-phpbrew_compiled
98.5%262741521531php-5.4.4-phpbrew_compiled
103.09%264473537113php-5.4.5-phpbrew_compiled
96.41%267710525813php-5.4.6-phpbrew_compiled
98.54%265773527653php-5.4.7-phpbrew_compiled
95.85%264166517360php-5.4.8-phpbrew_compiled
97.21%261104514916php-5.4.9-phpbrew_compiled
50%
updown
50%