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
49994 squared is  2499400036
49995 squared is  2499500025
49996 squared is  2499600016
49997 squared is  2499700009
49998 squared is  2499800004
49999 squared is  2499900001
总共占用的内存大小为:32 b
总共占用的时间为:5秒
总结:对比发现,可能由于脚本计算比较简单,运行的时间没啥太大变化。明显发现使用yield后占用内存的量要少很多。说明使用yield还是对性能提升很有帮助的,像类似的一次性拉取大数据量的数据都可以考虑使用yield实现(数据统计等).

猜你喜欢

转载自www.cnblogs.com/lisqiong/p/10209856.html