6

Title says it all.

Though the manual says you're better off to avoid a function call, I've also read $array[] is much slower than array_push(). Does anyone have any clarifications or benchmarks?

Thank you!

flag

2 Answers

17

No benchmarks, but I personally feel like $array[] is cleaner to look at, and honestly splitting hairs over milliseconds is pretty irrelevant unless you plan on appending hundreds of thousands of strings to your array.

Edit: Ran this code:

$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
    $array[] = $i;
}
print microtime(true) - $t;
print '<br>';
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
    array_push($array, $i);
}
print microtime(true) - $t;

The first method using $array[] is almost 50% faster than the second one.

Some benchmark results:

Run 1
0.0054171085357666 // array_push
0.0028800964355469 // array[]

Run 2
0.0054559707641602 // array_push
0.002892017364502 // array[]

Run 3
0.0055501461029053 // array_push
0.0028610229492188 // array[]

This shouldn't be surprising, as the PHP manual notes this:

If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

The way it is phrased I wouldn't be surprised if array_push is more efficient when adding multiple values. EDIT: Out of curiosity, did some further testing, and even for a large amount of additions, individual $array[] calls are faster than one big array_push. Interesting.

link|flag
I just always prefer to know which is the fastest way so when the day comes I will be asked to produce a high traffic site, I'll have some insight. Thanks for the answer. – alex Feb 18 '09 at 4:37
Micro-optimisations like these are rarely worth the effort. If you are writing it from scratch, do it how makes most sense, and only then, if it's a little slow to produce a page, profile it. The chances of getting all the way down to having to change something like this to speed things up is slight. – Alister Bulman May 31 '09 at 8:09
2

Word on the street is that [] is faster because no overhead for the function call. Plus, no one really likes PHP's array functions...

"Is it...haystack, needle....or is it needle haystack...ah, f*** it...[] = "

link|flag
1  
Huh? PHP's array functions are awesome. – cletus Feb 18 '09 at 4:56
Functionally they are awesome, yes, but he was referring to the inconsistent naming scheme. – ryeguy Feb 18 '09 at 5:03
You should turn on parameter hinting in your IDE. But I agree, some consistency would have been great. – Pim Jager Feb 18 '09 at 11:50
Yeh I'd spend quite a bit more time on php's manual were it not for parameter hinting.. or intellisense as some programs call it I believe? – alex Feb 18 '09 at 23:39

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.