【转载】为什么要使用 SPL中的 SplQueue实现队列

转自:https://www.cnblogs.com/itsuibi/p/10870608.html

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

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 倍

性能对比

虽然使用Array可以实现队列,但实际上性能会非常差。在一个大并发的服务器程序上,建议使用SplQueue作为队列数据结构。

100万条数据随机入队、出队,使用SplQueue仅用2312.345ms即可完成,而使用Array模拟的队列的程序根本无法完成测试,CPU一直持续在100%。

降低数据条数到1万条后(100倍),也需要260ms才能完成测试。

点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注