php, speed, comparison, array_push, array, arrays - john.mcclumpha

php : PHP speed comparison : array_push() vs array[]

Published: 2 yearss ago

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 10.32749986650.1879339218
0.32683706280.1882231236
0.32451891900.1875350475
Server 20.74681591990.4605989456
0.66913008690.3637771606
0.66544294360.3629529476
Server 30.11513996120.0791311264
0.11766195300.0834369659
0.11855411530.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 Source:

<?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);
}

?>

recent posts

Follow me on Twitter
Follow me on Facebook

Have you checked out Mister Wong? Simply the best way to manage your bookmarks online:
Mister Wong