Page 1 of 1

array_shift verus array_pop

Posted: Wed Dec 13, 2006 5:35 pm
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

Posted: Wed Dec 13, 2006 5:45 pm
by feyd
...and the results make complete sense.