139

What's better to use in PHP for appending an array member,

$array[] = $value;

or

array_push($array, $value);

?

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

1
  • 2
    $myArray[] = 123; This will be faster than array_push function. It directly adds the value into that array. Function has separate stack for that variables. and it may have that statement inside that function,. Commented Mar 12, 2010 at 9:32

9 Answers 9

180

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.

I 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. Out of curiosity, I did some further testing, and even for a large amount of additions, individual $array[] calls are faster than one big array_push. Interesting.

Sign up to request clarification or add additional context in comments.

14 Comments

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.
Just to make sure, since the code seems to mismatch the output, I verified that $array[] is indeed much faster, 300ms vs. 2000ms for 1M assignments on my machine. However, adding 20 items at once in array_push was about as fast as 20 $array[] =s.
@AlisterBulman Micro-optimizations are not worth the effort if you're thinking about going back through your whole codebase and 'optimizing' it. However, if you have several different ways of doing the same thing and are aware that one way is better (even just a little) than the others, you can make it your habit to use that way. Why wouldn't you do this?
@AlisterBulman I must strongly disagree, or at least partially, if you know better, write better, but don't put much effort to searching for possible micro-optimisation...
Reminder to any onlooker: not all minor optimization is the "premature optimization" that is the root of all evil as said Knuth. Some little faster things are just little faster things. remembering $array[]=$s is ok, combing your codebase for array_push isn't. Don't prematurely beat the premature-optimization-is-evil drum just because it exists.
|
45

The main use of array_push() is that you can push multiple values onto the end of the array.

It says in the documentation:

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.

1 Comment

That's right. Does anyone know a real world scenario where you have to add multiple values to an array at once? It seems to me that this must be a very rare scenario because I'm writing PHP since 2004 (where PHP4 was still actual) and I have never ever used it.
36

From the PHP documentation for array_push:

Note: 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.

Comments

24

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...[] = "

10 Comments

Huh? PHP's array functions are awesome.
Functionally they are awesome, yes, but he was referring to the inconsistent naming scheme.
You should turn on parameter hinting in your IDE. But I agree, some consistency would have been great.
I do agree on this. There is no consistency neither in the naming scheme (x_y or xy or y_x ...) nor in the parameters logic (pass the target object first, last, between arrays, strings and regexps, good luck to find a common rule!).
FWIW, I like the needle/haystack naming convention and find it easy to remember, as it goes in the same order as the phrase: "like finding a needle (1) in a haystack (2)"
|
7

One difference is that you can call array_push() with more than two parameters, i.e. you can push more than one element at a time to an array.

$myArray = array();
array_push($myArray, 1,2,3,4);
echo join(',', $myArray);

prints 1,2,3,4

Comments

1

A simple $myarray[] declaration will be quicker as you are just pushing an item onto the stack of items due to the lack of overhead that a function would bring.

Comments

1

Since "array_push" is a function and it called multiple times when it is inside the loop, it will allocate memory into the stack.

But when we are using $array[] = $value then we are just assigning a value to the array.

Comments

1

Second one is a function call so generally it should be slower than using core array-access features. But I think even one database query within your script will outweight 1000000 calls to array_push().

See here for a quick benchmark using 1000000 inserts: https://3v4l.org/sekeV

1 Comment

Can you substantiate your claim, e.g. with some rough calculations? Please respond by editing (changing) your answer, not here in comments (but without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
0

I just wan't to add : int array_push(...) returns the new number of elements in the array (PHP documentation). which can be useful and more compact than $myArray[] = ...; $total = count($myArray);.

Also array_push(...) is meaningful when variable is used as a stack.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.