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处理还是很有必要的。