Home > Backend Development > PHP Tutorial > How to use php generator

How to use php generator

小云云
Release: 2023-03-22 09:36:01
Original
1648 people have browsed it

Generally when we iterate a set of data, we need to create a data. If the array is large, it will consume a lot of performance and even cause insufficient memory to throw an error
For example:

//Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in D:\php\test\index.php on line 5range(1, 100000000);
Copy after login

PHP5 .5 introduces the concept of iterative generator. The concept of iteration has been in PHP for a long time, but the iterative generator is a new feature of PHP. It is similar to the iterative generator in python3. Take a look at the iterative generator of PHP5.5 How to define.
The following example implements a generator. Whenever an array element is generated, it is returned with the yield keyword, and the execution function is paused. When the function next method is executed, execution will continue from the last position yielded, as in the following example , only intermediate variables $i

function xrange($start, $limit, $step = 1) {    for ($i = $start; $i <= $limit; $i += $step) {
        yield $i;
    }
} 
foreach (xrange(1, 9, 1) as $number) {    echo "$number ";
}
Copy after login

xrange here is an iteration, the function is the same as range, if the range function is used, the internal implementation of the function will store the intermediate process of each iteration, that is, each Each intermediate variable has a memory space, so first of all, the memory space used by the program will be large, and allocating memory and recycling memory will lengthen the running time of the program. But if you use the xrange function implemented by yield, all intermediate variables in it only use one memory $i, so the time and space saved will become smaller.

So why does yield have such an effect? Thinking of yield in Lua, here is the concept of coroutine. In the Lua language, when the program reaches yield, a coroutine is used to record the context environment, and then the program operation rights are returned to the main function. When the main function calls resume, the coroutine will be re-awakened and the yield record will be read. context. This forms multi-coroutine operations at the programming language level. The same is true for yield here in PHP 5.5. When the program runs to yield, the current program calls up the coroutine to record the context, and then the main function continues to operate, except that keywords like resume are not used in PHP, but "using When the coroutine is called up. For example, the foreach iterator in the above example can evoke yield. So the above example can be understood.

Another example:

function xrange($start, $end, $step = 1) {    for ($i = $start; $i <= $end; $i += $step) {
      yield $i;
    }
}foreach (xrange(1, 1000000) as $num) {    echo $num, "\n";
}
Copy after login

Note the keyword: yield. It is this yield keyword that constructs an iterator. This is the difference between this function xrange and previous functions. Generally, a value is returned, and a value of yield means that this is an iterator. This iterator generates this value every time it loops, so it is called iterative generator. The iterative generator function can perform a foreach loop, each time Produce a value.

Before PHP5.5, iterators were constructed by defining classes to implement the Iterator interface. Constructing iterators through yield will further improve performance and save system overhead.

The advantages of this method are obvious. It allows you to process large data collections without loading them into memory at once, and you can even process infinitely large data streams.

As shown in the above example, the function of this iterator is to generate numbers from 1 to 1000000 and output them in a loop. If you use the previous method to generate the numbers from 1 to 1000000 into an array, it will be very It takes up memory because all the results are generated in advance instead of on demand when used. That is to say, when the xrange iterator is called, the functions inside are not actually run until each iteration.

Related recommendations:

How to use the PHP generator

Detailed explanation of the functions and usage of the PHP generator

php generator detailed introduction

The above is the detailed content of How to use php generator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template