Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `yield from $generator` and `return $generator`?

I have a function that gives back a generator. At the moment it uses yield from:

function foo()
{
    $generator = getGenerator();
    // some other stuff (no yields!)
    yield from $generator;
}

If I replace that yield from with a simple return, does that change anything in this case? Maybe in the execution? Or performance? Does yield from produces a new 'outer' iterator?

I know, in other cases yield from can be more flexible because I can use it several times and even mix it with simple yields, however that doesn't matter for my case.

like image 647
flori Avatar asked May 12 '16 13:05

flori


2 Answers

In your case, changing yield from to return gives the same result. However, if you have yield statement before return, it won't combine values from getGenerator().

function gen_1()
{
    yield 1;
}

function gen_2()
{
    return gen_1();
}

function gen_3()
{
    yield 2;
    return gen_1();
}

function gen_4()
{
    yield 2;
    yield from gen_1();
}

echo "testing gen_2\n";
foreach (gen_2() as $v) {
    echo $v  . "\n";
}

echo "testing gen_3\n";
foreach (gen_3() as $v) {
    echo $v  . "\n";
}

echo "testing gen_4\n";
foreach (gen_4() as $v) {
    echo $v  . "\n";
}

Output:

testing gen_2
1
testing gen_3
2
testing gen_4
2
1
like image 149
user2900416 Avatar answered Oct 14 '22 15:10

user2900416


When you use yield from once at the end of the method like you do above, this does not change things for what is returned by the method. But there is still a difference for the code inside the method: any code before the yield from is called when rewinding the iterator at the beginning of the iteration, while the code before the return is executed when calling the function, as this function is just a normal function now (actually, this is not specific to yield from. It is the behavior of yield. See https://3v4l.org/jnPvC for the proof).

The big advantage of yield from is that you can use it multiple times in the function, which combined values of all iterators into a single iterator.

like image 23
Christophe Coevoet Avatar answered Oct 14 '22 14:10

Christophe Coevoet