目录
How yield Works: A Simple Example
Real-World Use Case: Processing Large Files
Key Benefits of Generators
Advanced: Yielding Keys and Values
Limitations to Keep in Mind
Conclusion
首页 后端开发 php教程 带有PHP发电机和'收益”关键字的记忆效率迭代

带有PHP发电机和'收益”关键字的记忆效率迭代

Aug 03, 2025 am 01:38 AM
PHP Functions

使用PHP生成器和yield关键字可以有效处理大数据集,避免内存溢出;1. 生成器通过逐个yield值实现惰性求值,每次只保留一个值在内存中;2. 适用于逐行读取大文件等场景,如用fgets结合yield逐行处理日志或CSV文件;3. 支持键值对输出,可显式指定键名;4. 具有内存占用低、代码简洁、与foreach无缝集成等优点;5. 但存在无法倒带、不支持随机访问、不可重用等限制,需重新创建才能再次迭代;因此在需要遍历大量数据时应优先考虑使用生成器。

Memory-Efficient Iteration with PHP Generators and the `yield` Keyword

When dealing with large datasets in PHP, memory usage can quickly become a bottleneck—especially when you're loading thousands or even millions of records into arrays before processing them. This is where PHP generators and the yield keyword come in, offering a powerful way to iterate over data without loading everything into memory at once.

Memory-Efficient Iteration with PHP Generators and the `yield` Keyword

A generator is a special kind of function that allows you to iterate over a set of data without needing to build and store the entire dataset in memory. Instead of returning a value and ending execution, a generator yields values one at a time, pausing execution between each yield and resuming when the next value is requested.


How yield Works: A Simple Example

Instead of this memory-heavy approach:

Memory-Efficient Iteration with PHP Generators and the `yield` Keyword
function getNumbers($n) {
    $numbers = [];
    for ($i = 1; $i <= $n; $i  ) {
        $numbers[] = $i;
    }
    return $numbers;
}

foreach (getNumbers(1000000) as $num) {
    echo "$num\n";
}

This creates an array with 1 million integers in memory—expensive and unnecessary.

With a generator, you can do:

Memory-Efficient Iteration with PHP Generators and the `yield` Keyword
function getNumbers($n) {
    for ($i = 1; $i <= $n; $i  ) {
        yield $i;
    }
}

foreach (getNumbers(1000000) as $num) {
    echo "$num\n";
}

Now, only one value exists in memory at a time. The function pauses after each yield, waits for the next iteration, and then continues—massively reducing memory usage.


Real-World Use Case: Processing Large Files

One of the most practical applications of generators is reading large files (like CSVs or logs) line by line.

function readLines($file) {
    $handle = fopen($file, 'r');
    if (!$handle) {
        throw new Exception("Cannot open file: $file");
    }

    while (($line = fgets($handle)) !== false) {
        yield $line;
    }

    fclose($handle);
}

// Usage
foreach (readLines('huge-log-file.txt') as $line) {
    echo "Processing: " . trim($line) . "\n";
}

Without a generator, you might use file() to load all lines into an array—but that could crash with a large file. With yield, you process one line at a time, keeping memory usage low and predictable.


Key Benefits of Generators

  • Low memory footprint: Only one item is processed at a time.
  • Clean, readable code: Looks like a regular loop but behaves lazily.
  • Lazy evaluation: Values are generated only when needed.
  • Seamless integration with foreach: Generators return an object implementing the Iterator interface.

Advanced: Yielding Keys and Values

You can also specify keys explicitly:

function getKeyValuePairs() {
    yield 'first'  => 1;
    yield 'second' => 2;
    yield 'third'  => 3;
}

foreach (getKeyValuePairs() as $key => $value) {
    echo "$key: $value\n";
}

Or yield null keys when you want to filter or transform data on the fly.


Limitations to Keep in Mind

  • Cannot rewind after iteration: Once a generator is consumed, it's done (unless you recreate it).
  • No random access: You can't jump to the 100th item directly.
  • Not reusable: Generators are single-use unless wrapped or reinitialized.

For example:

$gen = getNumbers(3);
foreach ($gen as $n) { echo "$n "; } // 1 2 3
foreach ($gen as $n) { echo "$n "; } // Nothing—generator is already exhausted

Conclusion

Generators with yield are ideal for handling large datasets efficiently—whether you're reading files, querying databases, or processing streams of data. By producing values lazily, they help keep memory usage low and performance high.

Use them whenever you’re tempted to build a big array just to loop over it once. In many cases, you don’t need the whole dataset in memory—just one item at a time.

Basically: if you're looping, consider yielding.

以上是带有PHP发电机和'收益”关键字的记忆效率迭代的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Laravel 教程
1605
29
PHP教程
1510
276
解决PHP中递归功能的复杂问题 解决PHP中递归功能的复杂问题 Aug 02, 2025 pm 02:05 PM

递归函数是解决PHP中复杂问题的有效方法,特别适用于处理具有自相似结构的嵌套数据、数学计算和文件系统遍历。1.对于嵌套数组或菜单结构,递归能自动适应任意深度,通过基例(空子项)终止并逐层展开;2.计算阶乘和斐波那契数列时,递归直观实现数学定义,但朴素斐波那契存在性能问题,可通过记忆化优化;3.遍历目录时,递归可深入任意层级子目录,相比迭代更简洁,但需注意栈溢出风险;4.使用递归必须确保基例可达,避免无限调用,且在深度较大时应考虑使用迭代或显式栈替代以提升性能和稳定性。因此,当问题包含“更小的自身

了解PHP的通过参考:表现和陷阱 了解PHP的通过参考:表现和陷阱 Aug 03, 2025 pm 03:10 PM

Pass-by-referenceinPHPdoesnotimproveperformancewithlargearraysorobjectsduetocopy-on-writeandobjecthandles,soitshouldnotbeusedforthatpurpose;1.Usepass-by-referenceonlywhenyouneedtomodifytheoriginalvariable,suchasswappingvaluesorreturningmultiplevalues

掌握PHP封闭和词汇范围的'使用”关键字 掌握PHP封闭和词汇范围的'使用”关键字 Aug 01, 2025 am 07:41 AM

phpClosureswitheSeyKeyWordEnableLexicalScopingByCapturingVariables fromTheparentsCope.1.ClosuresAreAreAnMonyMousfunctionsThatCanAccessexCessexcessexCessexternalVariablesviause.2.ByDefault,variablesInusearePassedByvalue; tomodifythemexternally;

模拟PHP中模拟功能过载的技术 模拟PHP中模拟功能过载的技术 Aug 03, 2025 pm 01:12 PM

PHP不支持像Java或C 那样的函数重载,但可通过多种技术模拟;1.使用默认参数和可选参数,通过为参数设置默认值实现不同调用方式;2.使用变长参数列表(如...操作符),根据参数数量执行不同逻辑;3.在函数内部进行类型检查,根据参数类型改变行为;4.利用PHP8 的命名参数,通过显式命名跳过可选参数并提高可读性;5.基于参数模式分发,通过判断参数数量和类型路由到不同处理函数,适用于复杂场景;这些方法各有权衡,应根据实际需求选择以保证代码清晰和可维护。

回调的演变:php 8.1中的头等舱可呼叫语法 回调的演变:php 8.1中的头等舱可呼叫语法 Aug 03, 2025 am 10:00 AM

php8.1didnotintroducefirst classCallablesyntax; thisFeatureIscomingInphp8.4.4.1.priortophp8.4,callbackssusedstrings,阵列,orclos URES,WERERERROR-PRONEANDLACKEDIDEDIDESUPPORT.2.PHP8.1IMPREVEDTHEECOSYSTEMSTEMSTEMSTEMSTEMSTEMWITHENUMS,纤维和Bettertypingbutdidnotnotchangecalla

用`__invoke`魔法方法在PHP中创建可呼叫的对象 用`__invoke`魔法方法在PHP中创建可呼叫的对象 Aug 06, 2025 am 09:29 AM

The__invokemagicmethodinPHPallowsanobjecttobecalledasafunction,enablingittoactlikeacallable.2.Itisdefinedwithinaclassandautomaticallytriggeredwhentheobjectisinvokedwithparenthesesandarguments.3.Commonusecasesincludestatefulcallables,strategypatterns,

带有PHP发电机和'收益”关键字的记忆效率迭代 带有PHP发电机和'收益”关键字的记忆效率迭代 Aug 03, 2025 am 01:38 AM

使用PHP生成器和yield关键字可以有效处理大数据集,避免内存溢出;1.生成器通过逐个yield值实现惰性求值,每次只保留一个值在内存中;2.适用于逐行读取大文件等场景,如用fgets结合yield逐行处理日志或CSV文件;3.支持键值对输出,可显式指定键名;4.具有内存占用低、代码简洁、与foreach无缝集成等优点;5.但存在无法倒带、不支持随机访问、不可重用等限制,需重新创建才能再次迭代;因此在需要遍历大量数据时应优先考虑使用生成器。

拥抱功能编程:PHP中的高阶功能 拥抱功能编程:PHP中的高阶功能 Aug 03, 2025 am 02:12 AM

高级functionsInphpareFunctionsThatAcceptotherfunctionsAsArgumentsReTurnTherThemasSresults,EnablingFunctionalProgrammingmingtechniqunes.2.phpsupportspasspasspasspasspasspassingfunctionsasargumentsAsargumentsCallbacks,AsdymentyByBycustMustionsLakeMfunctionsLikeLikeFilterRakeFilterArrarayAndBuiltBuiltBuiltBuiltBuilt-Infun-infun

See all articles