A simple benchmark (PHP 8.1.9 + macOS 12.4)
<?php
ini_set('memory_limit', -1);
$times = 25_000;
$length = 256;
$arr = [];
$random = random_bytes(($times + $length) / 2);
$random = bin2hex($random);
for ($i = 0; $i < $times; $i++) {
$arr[$i] = substr($random, $i, $length);
}
$shiftTimer = -hrtime(true);
for ($i = 0; $i < $times; $i++) {
$value = array_shift($arr);
}
$shiftTimer += hrtime(true);
for ($i = 0; $i < $times; $i++) {
$arr[$i] = substr($random, $i, $length);
}
$reverseTimer = -hrtime(true);
for ($i = 0; $i < $times; $i++) {
$arr = array_reverse($arr);
$value = array_pop($arr);
$arr = array_reverse($arr);
}
$reverseTimer += hrtime(true);
for ($i = 0; $i < $times; $i++) {
$arr[$i] = substr($random, $i, $length);
}
$popTimer = -hrtime(true);
$arr = array_reverse($arr);
for ($i = 0; $i < $times; $i++) {
$value = array_pop($arr);
}
$popTimer += hrtime(true);
for ($i = 0; $i < $times; $i++) {
$arr[$i] = substr($random, $i, $length);
}
$keyTimer = -hrtime(true);
reset($arr);
for ($i = 0; $i < $times; $i++) {
$key = key($arr);
$val = $arr[$key];
unset($arr[$key]);
}
$keyTimer += hrtime(true);
print_r([
'shift' => $shiftTimer / (10 ** 9),
'reverse' => $reverseTimer / (10 ** 9),
'pop' => $popTimer / (10 ** 9),
'key' => $keyTimer / (10 ** 9),
]);
?>
Results interpretation:
On an array of 25,000 unique items, each item a string of 256 byte:
and key() + unset() is very fast.
array_shift() is ~400 times slower
array_reverse() + array_pop() + array_reverse() is ~5,000 times slower.
p.s. I'm implementing a queue, so I need to add another array_reverse() after array_pop() which makes it extremely slow inside a loop. array_reverse() + array_pop() has no use for me, I just added for sake of checking it's performance. It is as fast as key() + unset().