What's the performance difference (if there is any) between these three approaches, both used to transform an array to another array?
- Using
foreach
- Using
array_map
with lambda/closure function - Using
array_map
with 'static' function/method - Is there any other approach?
To make myself clear, let's have look at the examples, all doing the same - multiplying the array of numbers by 10:
$numbers = range(0, 1000);
Foreach
$result = array();
foreach ($numbers as $number) {
$result[] = $number * 10;
}
return $result;
Map with lambda
return array_map(function($number) {
return $number * 10;
}, $numbers);
Map with 'static' function, passed as string reference
function tenTimes($number) {
return $number * 10;
}
return array_map('tenTimes', $numbers);
Is there any other approach? I will be happy to hear actually all differences between the cases from above, and any inputs why one should be used instead of others.
FWIW, I just did the benchmark since poster didn't do it. Running on PHP 5.3.10 + XDebug.
UPDATE 2015-01-22 compare with mcfedr's answer below for additional results without XDebug and a more recent PHP version.
I get pretty consistent results with 1M numbers across a dozen attempts:
Supposing the lackluster speed of the map on closure was caused by the closure possibly being evaluated each time, I also tested like this:
But the results are identical, confirming that the closure is only evaluated once.
2014-02-02 UPDATE: opcodes dump
Here are the opcode dumps for the three callbacks. First
useForeach()
:Then the
useMapClosure()
and the closure it calls:
then the
useMapNamed()
function:and the named function it calls,
_tenTimes()
: