While reworking some of my older code to help make it more portable (and OO'd) I found myself questioning whether or not to use array_push or the array[] method to add item(s) to an existing array.
Keeping in mind that this was a one-dimensional array containing only integers I couldn't see any clear advantage for either method - so it came down to some benchmarking.
I wrote a short script to go through and add 100,000 integers to an array using each method and measure the time taken for each to execute (source below).
I then ran this test several times on a few different machines to acheive the following results: (note only 1 of these is a 'production' machine - hence the other two seem 'slow')
| array_push() | array[] | |
| Server 1 | 0.3274998665 | 0.1879339218 |
| 0.3268370628 | 0.1882231236 | |
| 0.3245189190 | 0.1875350475 | |
| Server 2 | 0.7468159199 | 0.4605989456 |
| 0.6691300869 | 0.3637771606 | |
| 0.6654429436 | 0.3629529476 | |
| Server 3 | 0.1151399612 | 0.0791311264 |
| 0.1176619530 | 0.0834369659 | |
| 0.1185541153 | 0.0826609135 |
As you can see - the array[] method is much quicker - on average 41% faster - than using array_push().
Conclusion: in a simple instance such as the one demonstrated above, the array[] method of adding items to an array in PHP is substantially faster than using array_push. While the operations themselves don't take much time at all (remember, the times above are for executing each operation 100,000 times) - the compounding effect of many of these such requests on a server with a lot of traffic/activity could make a substantial difference to overall load and speed.
<?php
$items = 100000;
$array = array();
$start = microtime_float();
for ($i = 1; $i <= $items; $i++)
{
array_push($array, $i);
}
$end = microtime_float();
echo "using <strong>array_push</strong> for " . number_format($items,0) . " items took " . number_format(($end-$start),10) . " seconds.<br />";
unset($array);
$array = array();
$start2 = microtime_float();
for($i = 1; $i <= $items; $i++)
{
$array[] = $i;
}
$end2 = microtime_float();
echo "using <strong>array[]</strong> for " . number_format($items,0) . " items took " . number_format(($end2-$start2),10) . " seconds.";
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
?>