抽象测试。
<?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 "时间: ", bcsub($end_time, $start_time, 4), "\n";
echo "内存 (字节): ", memory_get_peak_usage(true), "\n";
?>
结果
----------------------------------
| 时间 | 内存,MB |
----------------------------------
| 非生成器 | 2.1216 | 89.25 |
|---------------------------------
| 使用生成器 | 6.1963 | 8.75 |
|---------------------------------
| 差异 | < 192% | > 90% |
----------------------------------