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
array_map()
was internally represented as aforeach
- correct me if I'm wrong please. – Putuparray_map
is built-in method which handles the array in C level rather than opcode and then in C. P.S. as I see your $arrayOfNumbers loop.. I have to tell you this too: foreach is faster than while, while is faster than for. If you use it for iterating an array, use foreach. For is the slowest because it does 2 checks every iteration. First to check ending condition and secondly it's doing that ++$i. So try to useforeach(range(1,1000) as $i)
instead of that for and benchmark that. – Derryberry