What are the advantages of using a "Generator" (Yield) in PHP?

Asked

Viewed 1,798 times

9

As of PHP 5.5, the Generator. It can be used within a function from the keyword yield.

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

Example of the manual:

<?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 saving this memory and simplifying the use of a iterator, what are the other advantages of using the Generator in PHP?

1 answer

13


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 die within a function and leave another function, probably in a loop, manipulate this data without worrying about how it was obtained. You separate the mechanism from the business rule.

He also allows what’s called Lazy Evaluation where you only compute a sequence item 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. The generator saves memory and processing.

Another use is in the creation of state machine and corollaries since he can maintain status between calls of his executions. He has natural breaks.

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

The memory gain is relative. If you need all the generated and used sequence 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 a reason not to use it, but if it doesn’t provide a real advantage you have no reason to accept a overhead.

  • You are the guy :)

  • @Wallacemaxters You didn’t understand the other time I told you about the rush to accept an answer http://meta.pt.stackoverflow.com/q/494/101 :)

  • I don’t remember "again". But I’m reading here :)

  • http://answall.com/questions/49561/quais-s%C3%a3o-os-benef%C3%adcios-de-usar-https/49580#comment100347_49561

  • Ah, yes. I remembered. This is true, it ends up not giving opportunity to people who are open text in the browser click on "add a reply"

  • 1

    You can, but discourage, people want to have the opportunity for your answer to be accepted, when you accept it right away when someone posts an answer, you will hardly have a second, which potentially can help you more than the first. Of course you can trade, but most do not trade, so those who answer know that it is almost certain that he will not have the acceptance and can not even answer because of this. Also because you’re already satisfied, there’s no reason to put anything else.

  • I will attend to the tips to proceed as a good community user :)

  • I read the response and the comments and I was left with a question, which accumulated something I read earlier about Yield. It is similar to "Return" or does the same thing?

  • No, this is a typical mistake. It causes a return, but it is a mechanism that guards a state in order to continue where it left off. The yield in itself is only this, but it always works in conjunction with the return, so it is common to have only one command that does both things "simultaneously". If none of the answers helped fully understand, try asking an even more specific question.

  • more or less understood, I will ask a question to know the difference between Yield and Return, I think maybe can help me better :)

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.