SPL SplQueue

SplQueue

简介

SplQueue 类通过使用双链表类提供队列的主要功能。

队列:队列是一种特殊的线性表,特殊之处在于它之允许在表的前端(front) 进行删除操作,而在表的后端(rear)进行插入操作,和一样,队列是一种操作受限制的线性表。进行插入的端称为队尾,进行删除操作的端称为队头。

我们先来看一下队列是源代码:

<?php
<?php

/**
 * The SplQueue class provides the main functionalities of a queue implemented using a doubly linked list.
 * @link https://php.net/manual/en/class.splqueue.php
 */
class SplQueue extends SplDoublyLinkedList {


    /**
     * Adds an element to the queue. 入队列
     * @return void 
     */
    public function enqueue ($value) {}

    /**
     * Dequeues a node from the queue 出队列
     * @return mixed The value of the dequeued node.
     */
    public function dequeue () {}

    /**
     * Sets the mode of iteration  设置迭代模式
     * The direction of the iteration (either one or the other):
     * <b>SplDoublyLinkedList::IT_MODE_LIFO</b> (Stack style)
     * @return void
     */
    public function setIteratorMode ($mode) {}

}

队列在双链表的基础上增加了两个新方法enqueue()和dequeue();对应的操作就是入队列和出队列,和栈类一样,重写了setIteratorMode() 方法,同样是限制了迭代的方式,迭代方向限定为IT_MODE_FIFO,即为先进先出。

有人会有疑问,我是不是使用array_push 和 array_pop也可以完成队列的功能,接下来我们对比一下这两种方式的不同:

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;

var_dump('----------');

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

$queue = new SplQueue();
for ($i = 0;$i<100000;$i++){
	$data = "hello  $i\n";
	$queue->enqueue($data);
	if ($i % 100 == 99 and count($splq) > 100)
    {
        $popN = rand(10, 99);
        for ($j = 0; $j < $popN; $j++)
        {
            $queue->dequeue();
        }
    }
}

for ($i=0;$i < $queue->count();$i++){
    $queue->dequeue();
}

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

echo $et - $st;

 

上边使用传统数组的输出结果为53655,下面使用SplQueue类的结果为438。可见在随着数据量的增长,两者的差距会越来越大。可见在处理大量数据的时候,使用SPL处理还是很有必要的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值