array_shift verus array_pop

Ye' old general discussion board. Basically, for everything that isn't covered elsewhere. Come here to shoot the breeze, shoot your mouth off, or whatever suits your fancy.
This forum is not for asking programming related questions.

Moderator: General Moderators

Post Reply
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

array_shift verus array_pop

Post by Ollie Saunders »

I thought this was interesting enough to tell people about:

Code: Select all

function _microTimeFormattedDiffence($one, $two)
    {
        foreach (array('one', 'two') as $var) {
            list($usec, $sec) = explode(' ', $$var);
            $$var = $usec + $sec;
        }
        return round($two - $one, 3);
    }

$a = range(0, 5000);
$ta = microtime();
for ($i=0, $j = count($a); $i < $j; ++$i) {
    array_shift($a);
}
$tb = microtime();
echo _microTimeFormattedDiffence($ta, $tb), ' ';

$a = range(0, 5000);
$ta = microtime();
for ($i=0, $j = count($a); $i < $j; ++$i) {
    array_pop($a);
}
$tb = microtime();
echo _microTimeFormattedDiffence($ta, $tb);
Outputs:

Code: Select all

2.521 0.005
Summary: array_shift is 504.2 times slower than array_pop on an array of 5000 !!
:D
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

...and the results make complete sense.
Post Reply