php SplQueue php标准库 队列 和数组 性能差异

数组模拟队列

$t1   = microtime(true);
$arrq = array();
for ($i = 0; $i < 100000; $i++) {
    $data = "hello $i\n";
    array_push($arrq, $data);
    if ($i % 100 == 99 and count($arrq) > 100) {
        $popN = rand(10, 99);
        for ($j = 0; $j < $popN; $j++) {
            array_shift($arrq);
        }
    }
}
$popN = count($arrq);
for ($j = 0; $j < $popN; $j++) {
    array_shift($arrq);
}
$t2 = microtime(true);
echo ($t2 - $t1) . "\n";                               // 6.93s
echo (memory_get_usage() / 1024 / 1024) . 'MB' . "\n"; // 4.38M

SplQueue

$t1   = microtime(true);
$splq = new SplQueue;
for ($i = 0; $i < 100000; $i++) {
    $data = "hello $i\n";
    $splq->push($data);

    if ($i % 100 == 99 and count($splq) > 100) {
        $popN = rand(10, 99);
        for ($j = 0; $j < $popN; $j++) {
            $splq->shift();
        }
    }
}
$popN = $splq->count();
for ($j = 0; $j < $popN; $j++) {
    $splq->shift();
}
$t2 = microtime(true);
echo ($t2 - $t1) . "\n";                               // 0.03S
echo (memory_get_usage() / 1024 / 1024) . 'MB' . "\n"; // 0.38M

相关文章

此处评论已关闭