Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_map vs loop and operation

Tags:

php

spl

array-map

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

like image 406
Lizard Avatar asked Dec 06 '11 05:12

Lizard


People also ask

Is Array_filter faster than foreach?

Filter a set of values from a larger set? Most likely that array_filter() is faster than a hand-coded foreach -loop because it's a built-in function.

What is Array_map function in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.


2 Answers

To my knowledge php doesn't do anything asynchronously, in contrast to Sajith Amma's answer.

I suspect that this is actually due to differences in the lookup of $maxHeap->insert.

With the foreach loop the you are calling $maxHeap->insert within the current scope, the php interpreter has to look up maxHeap then lookup insert on the maxHeap instance. Within the scope of the script you are running there might be other variables which can make the lookup slower.

With the array_map the php interpreter knows it will be calling the exact same $maxHeap->insert, it can do the lookup just once and use the same 'code address' for the rest of the iterations.

like image 69
Jessie Ross Avatar answered Oct 07 '22 21:10

Jessie Ross


It is due to the difference between Callback functions and normal functions.

In 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.

like image 2
Sajith Amma Avatar answered Oct 07 '22 21:10

Sajith Amma