美文网首页
php生成器

php生成器

作者: 江江简书 | 来源:发表于2020-12-14 21:31 被阅读0次

    生成器在大内存存储处理的场景下,非常优雅,但是从时间维度上来看生成器有在用时间换空间的嫌疑,但是这也是一个非常不错的场景

    初探

    function test1()
    {
    for ($i = 0; $i < 3; $i++) {
    yield $i + 1;
    }
    yield 1000;
    yield 1001;
    }
    foreach (test1() as $t) {
    echo $t, PHP_EOL;
    }
    // 1
    // 2
    // 3
    // 1000
    // 1001
    
    • 生成器像return,但和return又有差距,return会中断下面的执行,而yield相当于是一次次的返回。

    生成器内存维度测试

    // 内存占用测试
    $start_time = microtime(true);
    function test2($clear = false)
    {
        $arr = [];
        if($clear){
        $arr = null;
        return;
    }
    
    for ($i = 0; $i < 1000000; $i++) {
        $arr[] = $i + 1;
    }
    
    return $arr;
    }
    
    $array = test2();
    foreach ($array as $val) {
    }
    
    $end_time = microtime(true);
    echo "time: ", bcsub($end_time, $start_time, 4), PHP_EOL;
    echo "memory (byte): ", memory_get_usage(true), PHP_EOL;
    
    
    $start_time = microtime(true);
    function test3()
    {
        for ($i = 0; $i < 1000000; $i++) {
            yield $i + 1;
        }
    }
    $array = test3();
    
    foreach ($array as $val) {
    }
    $end_time = microtime(true);
    echo "time: ", bcsub($end_time, $start_time, 4), PHP_EOL;
    echo "memory (byte): ", memory_get_usage(true), PHP_EOL;
    

    返回键值对

    function test5()
    {
        for ($i = 0; $i < 10; $i++) {
            yield 'key.' . $i => $i + 1;
        }
    }
    
    foreach (test5() as $k=>$t) {
        echo $k . ':' . $t, PHP_EOL;
    }
    

    参考文章:https://mp.weixin.qq.com/s/R3MtOvi-hQiCMfDzSj6bzw

    相关文章

      网友评论

          本文标题:php生成器

          本文链接:https://www.haomeiwen.com/subject/gypbgktx.html