What are the advantages of using a "generator" (yield) in PHP?

Starting with PHP 5.5, the generator was implemented in the language. It can be used within a function from the keyword yield.

In the manual , we have an example where one is compared to the range(0, 1000000) function (which would theoretically spend 100MB of memory) and an implementation of xrange through the generators (which would reduce memory consumption to 1 kilobyte).

Manual example:

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

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

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

/*
 * Note that both range() and xrange() result in the same
 * output below.
 */

echo 'Single digit odd numbers from range():  ';
foreach (range(1, 9, 2) as $number) {
    echo "$number ";
}
echo "\n";

echo 'Single digit odd numbers from xrange(): ';
foreach (xrange(1, 9, 2) as $number) {
    echo "$number ";
}
?>

In addition to the advantage of save this memory and simplify the use of a iterator , What are the other advantages of using the generator in PHP?

Author: Maniero, 2015-02-10

1 answers

In the background generators are not to save memory. This is another welcome side effect. They exist to create data sequences on demand.

His general idea is to be able to better control what happens between the generation of each element of the sequence.

One of the advantages is to produce code with better abstractions. You encapsulate the mechanism of how you get the data inside a function and leave another function, probably in a loop , to manipulate these data without worrying about how it was obtained. You separate the mechanism from the business rule.

It also allows what is called lazy evaluation in that you only exercise the computation of an item in the sequence when and if you will actually use it. Without the generator it is very common to generate huge data sequences, probably in lists or arrays , and spend a huge amount of time to generate all the elements and then just actually use some of them and discard the rest. We generator saves memory and processing.

Another use is in creating state machine and corotines since it manages to maintain state between calls of its executions. He has natural breaks.

The operation of a generator is more or less the same in all languages that have it. I already answered something about this in C # which has a pretty sophisticated generator. There are some good examples.

The gain in memory is relative. If you need the whole sequence generated and used at the same time, there is no gain (if you know what you are doing).

Generators are not great for all cases. They provoke in Little overhead . Not that this is reason not to use, but if it doesn't provide a real advantage you don't have to accept a overhead.

 13
Author: Maniero, 2017-04-13 12:59:42