抽象測試。
<?php
$start_time=microtime(true);
$array = array();
$result = '';
for($count=1000000; $count--;)
{
$array[]=$count/2;
}
foreach($array as $val)
{
$val += 145.56;
$result .= $val;
}
$end_time=microtime(true);
echo "時間: ", bcsub($end_time, $start_time, 4), "\n";
echo "記憶體 (位元組): ", memory_get_peak_usage(true), "\n";
?>
<?php
$start_time=microtime(true);
$result = '';
function it()
{
for($count=1000000; $count--;)
{
yield $count/2;
}
}
foreach(it() as $val)
{
$val += 145.56;
$result .= $val;
}
$end_time=microtime(true);
echo "time: ", bcsub($end_time, $start_time, 4), "\n";
echo "memory (byte): ", memory_get_peak_usage(true), "\n";
?>
結果
----------------------------------
| 時間 | 記憶體 (MB) |
----------------------------------
| 非產生器 | 2.1216 | 89.25 |
|---------------------------------
| 使用產生器 | 6.1963 | 8.75 |
|---------------------------------
| 差異 | < 192% | > 90% |
----------------------------------