Using:
for($i=1; $i<= 10000; ++$i) {
$arrayOfNumbers[] = rand(1, 99999);
}
Can some explain why there is such a speed difference:
array_map(array($maxHeap, 'insert'), $arrayOfNumbers);
# Avg Time: 0.92856907844543s
# against
foreach($arrayOfNumbers as $number) {
$maxHeap->insert($number);
}
# Avg Time: 1.3148670101166
$maxHeap
being an object class MaxHeap extends SplMaxHeap
Thanks in advance for your explanation!
Source: Tips4all
It is due to the difference between Callback functions and normal functions.
ReplyDeleteIn the second one, iteration of array using foreach, each iteration calls "insert" function and wait for the execution (function return control) and proceed to next iteration.
But in the array_map function, "insert" happens as callback function, it calls "insert" and don't wait for the result and call insert with next item in the array. So it is faster.
Hope it helps.
Using objects is slightly slower. Are your three cases comparable at all? What does this method "insert"? Adding values to an array?
ReplyDeletehttp://atomized.org/2009/02/really-damn-slow-a-look-at-php-objects/
And when your are on reading this, you can look at this one also ;)
http://atomized.org/2005/04/php-performance-best-practices/