亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
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
Home Backend Development PHP Tutorial Memory-Efficient Iteration with PHP Generators and the `yield` Keyword

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

Aug 03, 2025 am 01:38 AM
PHP Functions

Use the PHP generator and yield keywords to effectively process large data sets to avoid memory overflow; 1. The generator realizes lazy evaluation by yield value, leaving only one value in memory at a time; 2. It is suitable for scenarios such as reading large files line by line, such as using fgets combined with yield line by line, and processing logs or CSV files line by line; 3. It supports key-value pair output, and can explicitly specify key names; 4. It has the advantages of low memory footprint, concise code, and seamless integration with foreach; 5. However, there are restrictions such as inability to rewind, do not support random access, and cannot be reused, and it needs to be recreated before iteration is performed; therefore, when it is necessary to traverse a large amount of data, the use of generators should be given priority.

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 return ing a value and ending execution, a generator yields values one at a time, pausing execution between each yield and recovering 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, &#39;r&#39;);
    if (!$handle) {
        throw new Exception("Cannot open file: $file");
    }

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

    fclose($handle);
}

// Usage
foreach (readLines(&#39;huge-log-file.txt&#39;) 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 &#39;first&#39; => 1;
    yield &#39;second&#39; => 2;
    yield &#39;third&#39; => 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.

The above is the detailed content of Memory-Efficient Iteration with PHP Generators and the `yield` Keyword. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solving Complex Problems with Recursive Functions in PHP Solving Complex Problems with Recursive Functions in PHP Aug 02, 2025 pm 02:05 PM

Recursive functions are an effective way to solve complex problems in PHP, especially suitable for handling nested data, mathematical calculations, and file system traversals with self-similar structures. 1. For nested arrays or menu structures, recursion can automatically adapt to any depth, terminate through the basis example (empty child) and expand layer by layer; 2. When calculating factorials and Fibonacci sequences, recursion intuitively implements mathematical definition, but naive Fibonacci has performance problems and can be optimized through memory; 3. When traversing the directory, recursion can penetrate into any level subdirectories, which is simpler than iteration, but attention should be paid to the risk of stack overflow; 4. When using recursion, it is necessary to ensure that the base case is reachable, avoid infinite calls, and when the depth is large, it should be considered to use iteration or explicit stack substitution to improve performance and stability. So when the problem contains "smaller itself

Embracing Functional Programming: Higher-Order Functions in PHP Embracing Functional Programming: Higher-Order Functions in PHP Aug 03, 2025 am 02:12 AM

Higher-orderfunctionsinPHParefunctionsthatacceptotherfunctionsasargumentsorreturnthemasresults,enablingfunctionalprogrammingtechniques.2.PHPsupportspassingfunctionsasargumentsusingcallbacks,asdemonstratedbycustomfunctionslikefilterArrayandbuilt-infun

Memory-Efficient Iteration with PHP Generators and the `yield` Keyword Memory-Efficient Iteration with PHP Generators and the `yield` Keyword Aug 03, 2025 am 01:38 AM

Use the PHP generator and yield keywords to effectively process large data sets to avoid memory overflow; 1. The generator realizes lazy evaluation by yield value, leaving only one value in memory at a time; 2. It is suitable for scenarios such as reading large files line by line, such as using fgets combined with yield line by line, and processing logs or CSV files line by line; 3. Support key-value pair output, and explicitly specify key names; 4. It has the advantages of low memory footprint, concise code, and seamless integration with foreach; 5. However, there are restrictions such as inability to rewind, do not support random access, and cannot be reused, and it needs to be recreated before iteration is performed; therefore, when it is necessary to traverse a large amount of data, the use of generators should be given priority.

Mastering PHP Closures and the `use` Keyword for Lexical Scoping Mastering PHP Closures and the `use` Keyword for Lexical Scoping Aug 01, 2025 am 07:41 AM

PHPclosureswiththeusekeywordenablelexicalscopingbycapturingvariablesfromtheparentscope.1.Closuresareanonymousfunctionsthatcanaccessexternalvariablesviause.2.Bydefault,variablesinusearepassedbyvalue;tomodifythemexternally,use&$variableforreference

Harnessing the Power of Variadic Functions with the Splat Operator Harnessing the Power of Variadic Functions with the Splat Operator Aug 03, 2025 am 06:21 AM

Thesplatoperator(...)inPHPisusedtocollectmultipleargumentsintoanarraywhendefiningafunctionandtounpackarraysoriterablesintoindividualargumentswhencallingafunction.2.Whendefiningafunction,suchasfunctionsum(...$numbers),allpassedargumentsarecollectedint

The Evolution of Callbacks: First-Class Callable Syntax in PHP 8.1 The Evolution of Callbacks: First-Class Callable Syntax in PHP 8.1 Aug 03, 2025 am 10:00 AM

PHP8.1didnotintroducefirst-classcallablesyntax;thisfeatureiscominginPHP8.4.1.PriortoPHP8.4,callbacksusedstrings,arrays,orClosures,whichwereerror-proneandlackedIDEsupport.2.PHP8.1improvedtheecosystemwithenums,fibers,andbettertypingbutdidnotchangecalla

Understanding PHP's Pass-by-Reference: Performance and Pitfalls Understanding PHP's Pass-by-Reference: Performance and Pitfalls Aug 03, 2025 pm 03:10 PM

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

Techniques for Simulating Function Overloading in PHP Techniques for Simulating Function Overloading in PHP Aug 03, 2025 pm 01:12 PM

PHP does not support function overloading like Java or C, but can be simulated through a variety of techniques; 1. Use default parameters and optional parameters to achieve different calling methods by setting default values for parameters; 2. Use variable-length parameter list (such as... operators), perform different logic according to the number of parameters; 3. Perform type checks within the function and change behavior according to the parameter type; 4. Use PHP8's named parameters to skip optional parameters by explicit naming and improve readability; 5. Based on parameter mode distribution, route to different processing functions by judging the number and type of parameters, which is suitable for complex scenarios; these methods have trade-offs and should be selected according to actual needs to ensure clear and maintainable code.

See all articles