Why to use SplQueue in SPL to implement queues

Today, the SPL standard library of php involves data structure, in which SplQueue is used to achieve the queue effect. But when I first contacted php, I learned that the array_push and array_pop of array can achieve the queue effect. So is this in SPL very weak?? Later, after querying the data and running the following program, we found that in terms of performance, the data structure with SPL is much better than the queue simulated with array

Array array simulation queue, processing 100000 tasks

list($t1, $t2) = explode(' ', microtime());
$st = (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
$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);
}

list($t1, $t2) = explode(' ', microtime());
$et = (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);

echo $et - $st;

The average value of three times of execution is 3900 ms

Use SplQueue

list($t1, $t2) = explode(' ', microtime());
$st = (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);

$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();
        }
    }
}
list($t1, $t2) = explode(' ', microtime());
$et = (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);

echo $et - $st;

The average value of three times of execution is 117 ms

33 times better performance

As for the spl standard library, it seems that more research should be done. Since there is such a library in the document, there must be something unique about it!

Reference documents: https://wiki.swoole.com/wiki/page/507.html

Tags: PHP

Posted on Sun, 10 Nov 2019 09:52:30 -0800 by mmj