使用PHP生成器和yield關(guān)鍵字可以有效處理大數(shù)據(jù)集,避免內(nèi)存溢出;1. 生成器通過(guò)逐個(gè)yield值實(shí)現(xiàn)惰性求值,每次只保留一個(gè)值在內(nèi)存中;2. 適用於逐行讀取大文件等場(chǎng)景,如用fgets結(jié)合yield逐行處理日誌或CSV文件;3. 支持鍵值對(duì)輸出,可顯式指定鍵名;4. 具有內(nèi)存佔(zhàn)用低、代碼簡(jiǎn)潔、與foreach無(wú)縫集成等優(yōu)點(diǎn);5. 但存在無(wú)法倒帶、不支持隨機(jī)訪問(wèn)、不可重用等限制,需重新創(chuàng)建才能再次迭代;因此在需要遍歷大量數(shù)據(jù)時(shí)應(yīng)優(yōu)先考慮使用生成器。
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 .

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 return
ing 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:

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:

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 theIterator
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發(fā)電機(jī)和'收益”關(guān)鍵字的記憶效率迭代的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門(mén)文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6
視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版
神級(jí)程式碼編輯軟體(SublimeText3)

遞歸函數(shù)是解決PHP中復(fù)雜問(wèn)題的有效方法,特別適用於處理具有自相似結(jié)構(gòu)的嵌套數(shù)據(jù)、數(shù)學(xué)計(jì)算和文件系統(tǒng)遍歷。 1.對(duì)於嵌套數(shù)組或菜單結(jié)構(gòu),遞歸能自動(dòng)適應(yīng)任意深度,通過(guò)基例(空子項(xiàng))終止並逐層展開(kāi);2.計(jì)算階乘和斐波那契數(shù)列時(shí),遞歸直觀實(shí)現(xiàn)數(shù)學(xué)定義,但樸素斐波那契存在性能問(wèn)題,可通過(guò)記憶化優(yōu)化;3.遍歷目錄時(shí),遞歸可深入任意層級(jí)子目錄,相比迭代更簡(jiǎn)潔,但需注意棧溢出風(fēng)險(xiǎn);4.使用遞歸必須確保基例可達(dá),避免無(wú)限調(diào)用,且在深度較大時(shí)應(yīng)考慮使用迭代或顯式棧替代以提升性能和穩(wěn)定性。因此,當(dāng)問(wèn)題包含“更小的自身

使用PHP生成器和yield關(guān)鍵字可以有效處理大數(shù)據(jù)集,避免內(nèi)存溢出;1.生成器通過(guò)逐個(gè)yield值實(shí)現(xiàn)惰性求值,每次只保留一個(gè)值在內(nèi)存中;2.適用於逐行讀取大文件等場(chǎng)景,如用fgets結(jié)合yield逐行處理日誌或CSV文件;3.支持鍵值對(duì)輸出,可顯式指定鍵名;4.具有內(nèi)存佔(zhàn)用低、代碼簡(jiǎn)潔、與foreach無(wú)縫集成等優(yōu)點(diǎn);5.但存在無(wú)法倒帶、不支持隨機(jī)訪問(wèn)、不可重用等限制,需重新創(chuàng)建才能再次迭代;因此在需要遍歷大量數(shù)據(jù)時(shí)應(yīng)優(yōu)先考慮使用生成器。

高級(jí)functionsInphpareFunctionsThatAcceptotherfunctionsAsArgumentsReTurnTherThemasSresults,EnablingFunctionalProgrammingmingtechniqunes.2.phpsupportspasspasspasspasspasspassingfunctionsasargumentsAsargumentsCallbacks,AsdymentyByBycustMustionsLakeMfunctionsLikeLikeFilterRakeFilterArrarayAndBuiltBuiltBuiltBuiltBuilt-Infun-infun

php8.1didnotintroducefirst classCallablesyntax; thisFeatureIscomingInphp8.4.4.1.priortophp8.4,callbackssusedstrings,陣列,orclos URES,WERERERROR-PRONEANDLACKEDIDEDIDESUPPORT.2.PHP8.1IMPREVEDTHEECOSYSTEMSTEMSTEMSTEMSTEMSTEMWITHENUMS,纖維和Bettertypingbutdidnotnotchangecalla

TheSplatoperator(...)InphpisusedTocollectMultipleArgeargumentsIntoAnArrayWhenDefiningAfiningAfinctionAndAfinctionandTounpackArsorableSIntoMintoIndoIvidualgumentsWhenCallingAfunction.2.WhendeFiningAfninction.2.WhenDefiningAfninction.whendefiningafunction,siseAsAsfunctionsum(... $ numbess),AllpassEdeDeDargumentsArecolleCollecolleColleColleCollecollectectedInt

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

PHP不支持像Java或C 那樣的函數(shù)重載,但可通過(guò)多種技術(shù)模擬;1.使用默認(rèn)參數(shù)和可選參數(shù),通過(guò)為參數(shù)設(shè)置默認(rèn)值實(shí)現(xiàn)不同調(diào)用方式;2.使用變長(zhǎng)參數(shù)列表(如...操作符),根據(jù)參數(shù)數(shù)量執(zhí)行不同邏輯;3.在函數(shù)內(nèi)部進(jìn)行類型檢查,根據(jù)參數(shù)類型改變行為;4.利用PHP8 的命名參數(shù),通過(guò)顯式命名跳過(guò)可選參數(shù)並提高可讀性;5.基於參數(shù)模式分發(fā),通過(guò)判斷參數(shù)數(shù)量和類型路由到不同處理函數(shù),適用於復(fù)雜場(chǎng)景;這些方法各有權(quán)衡,應(yīng)根據(jù)實(shí)際需求選擇以保證代碼清晰和可維護(hù)。

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