循环数据,查看内存使用对比
<?php
namespace Hjj\DesignPatterns\Tests;
use PHPUnit\Framework\TestCase;
class YieldTest extends TestCase
{
// public function makeRange($length) {
// $dataSet = [];
// for ($i=0; $i<$length; $i++) {
// $dataSet[] = $i;
// }
// return $dataSet;
// }
// public function testLongFor() {
//
// $customRange = $this->makeRange(1000000);
// foreach ($customRange as $i) {
// echo $i . PHP_EOL;
// }
// $this->assertSame(1,1);
// }
//
public function makeRangeByYield($length) {
for ($i=0; $i<$length; $i++) {
yield $i;
}
}
public function testYield() {
foreach ($this->makeRangeByYield(1000000) as $i) {
echo $i . PHP_EOL;
}
$this->assertSame(1,1);
}
}
第一个,直接循环
// Time: 00:01.084, Memory: 72.00 MB
第二个,使用yield
// Time: 00:01.128, Memory: 36.00 MB
使用生成器迭代流资源(文件、音频等)
function getRows($file) {
$handle = fopen($file, 'rb');
if ($handle == FALSE) {
throw new Exception();
}
while (feof($handle) === FALSE) {
yield fgetcsv($handle);
}
fclose($handle);
}
foreach (getRows($file) as $row) {
print_r($row);
}