数组模拟队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$t1   = microtime(true);
$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);
}
$t2 = microtime(true);
echo ($t2 - $t1) . "\n"; // 6.93s
echo (memory_get_usage() / 1024 / 1024) . 'MB' . "\n"; // 4.38M

SplQueue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$t1   = microtime(true);
$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();
}
}
}
$popN = $splq->count();
for ($j = 0; $j < $popN; $j++) {
$splq->shift();
}
$t2 = microtime(true);
echo ($t2 - $t1) . "\n"; // 0.03S
echo (memory_get_usage() / 1024 / 1024) . 'MB' . "\n"; // 0.38M