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 yield
s, however that doesn't matter for my case.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With