本文实例讲述了php使用yield对性能提升的测试。分享给大家供大家参考,具体如下:
生成器提供了一种更容易的方法来实现简单的对象迭代,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大大降低。生成器允许你在 foreach 代码块中写代码来迭代一组数据而不需要在内存中创建一个数组, 那会使你的内存达到上限,或者会占据可观的处理时间。相反,你可以写一个生成器函数,就像一个普通的自定义函数一样, 和普通函数只返回一次不同的是, 生成器可以根据需要 yield 多次,以便生成需要迭代的值。
有两个php文件,demo1.php与demo2.php,两种不同的方式实现求0,到5000之间的数字的平方值并输出,并打印脚本运行的时间与使用的内存大小。
demo1.php
<?php $startMemory = memory_get_usage(); $startTime = time(); function convert($size) { $unit=array('b','kb','mb','gb','tb','pb'); return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; } function squares($start,$stop){ $info = ''; $square = 0; for($i=$start;$i<$stop;$i++){ $square = $i*$i; $info .= $i.' squared is '.$square.PHP_EOL; } return $info; } $info = squares(0,50000); echo $info.PHP_EOL; $endTime = time(); $useTime = $endTime-$startTime; $endMemory = memory_get_usage(); $useMemory = $endMemory-$startMemory; echo "总共占用的内存大小为:".convert($useMemory).PHP_EOL; echo "总共占用的时间为:".$useTime.'秒'.PHP_EOL;
运行结果如下:
49993 squared is 2499300049
49994 squared is 2499400036
49995 squared is 2499500025
49996 squared is 2499600016
49997 squared is 2499700009
49998 squared is 2499800004
49999 squared is 2499900001总共占用的内存大小为:1.28 mb
总共占用的时间为:5秒
demo2.php
<?php $startMemory = memory_get_usage(); $startTime = time(); function convert($size) { $unit=array('b','kb','mb','gb','tb','pb'); return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; } function squares($start,$stop){ for($i = $start;$i<$stop;$i++){ yield $i=>$i*$i; } } foreach(squares(0,50000) as $n=>$square ){ echo $n.' squared is '.$square.PHP_EOL; } $endTime = time(); $useTime = $endTime-$startTime; $endMemory = memory_get_usage(); $useMemory = $endMemory-$startMemory; echo "总共占用的内存大小为:".convert($useMemory).PHP_EOL; echo "总共占用的时间为:".$useTime.'秒'.PHP_EOL;
运行demo2.php结果如下:
49988 squared is 2498800144
49989 squared is 2498900121
49990 squared is 2499000100
49991 squared is 2499100081
49992 squared is 2499200064
49993 squared is 2499300049