php yield 关键词使用

一懒众衫小,薪尽自然凉。

生成器提供了一种更容易的方法来实现简单的对象迭代,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大大降低

看到这个词 yield, 相信很多人都比较陌生,也许在其他语言中看到的比在php中看到的更多,代表的是yield 生成器修饰词;

直接上代码看实现的功能

function xrange($start, $limit, $step = 1) {
    if ($start <= $limit) {
        if ($step <= 0) {
            throw new LogicException('Step must be positive');
        }

        for ($i = $start; $i <= $limit; $i += $step) {
            yield $i;
        }
    } else {
        if ($step >= 0) {
            throw new LogicException('Step must be negative');
        }

        for ($i = $start; $i >= $limit; $i += $step) {
            yield $i;
        }
    }
}

该函数和 range 函数功能是一样的,看起来没有啥差别,但是随机的数据很大的话,就显示出差别来了

https://www.php.net/manual/zh/language.generators.overview.php

官网手册上有对应的例子,可以对比一下,执行时间,内存占用等等

原文地址:https://www.cnblogs.com/fangdada/p/15042447.html