当前位置: 移动技术网 > IT编程>开发语言>PHP > 为什么要使用 SPL中的 SplQueue实现队列

为什么要使用 SPL中的 SplQueue实现队列

2019年05月16日  | 移动技术网IT编程  | 我要评论

今天看php的spl标准库部分里面涉及到数据结构其中有 splqueue 来实现队列效果,但是我刚接触php的时候学习到的是 使用array的 array_push 和 array_pop 就可以实现队列效果啦啊,那么说 spl中的这个是不是显得很鸡肋呢??后来进过查询资料并且实际运行一下程序后发现,其实在性能方面,使用spl的数据结构比使用array模拟出来的队列在性能上强很多:

  array数组模拟队列,处理100000任务

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;

执行三次取平均值为:3900 ms

  使用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;

执行三次取平均值为:117 ms

性能提升 33 倍

关于spl标准库这块,看来还要多研究研究,既然文档中有这个库,那么肯定有它独特的地方!

参考文档 :

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网