Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Comparison of generator with foreach and yield from
<?php declare(strict_types=1);
class Test
{
private $arr = [];
public function __construct()
{
for ( $i = 0; $i < 10000; $i++ )
{
$this->arr["key{$i}"] = "value{$i}";
}
}
public function getIterator() : Iterator
{
foreach ( $this->arr as $key => $value )
{
yield $key => $value;
}
}
}
$test = new Test();
foreach ( $test->getIterator() as $key => $value )
{
echo $key, ' => ', $value, "\n";
}
<?php declare(strict_types=1);
class Test
{
private $arr = [];
public function __construct()
{
for ( $i = 0; $i < 10000; $i++ )
{
$this->arr["key{$i}"] = "value{$i}";
}
}
public function getIterator() : Iterator
{
yield from $this->arr;
}
}
$test = new Test();
foreach ( $test->getIterator() as $key => $value )
{
echo $key, ' => ', $value, "\n";
}
@hollodotme

This comment has been minimized.

Copy link
Owner Author

commented Nov 7, 2018

A blackfire performance comparison with 100 samples for each script can be found here: https://blackfire.io/profiles/compare/cef5b2d8-a511-443b-bad7-8a49a9918258/graph

@hollodotme

This comment has been minimized.

Copy link
Owner Author

commented Nov 7, 2018

When looking at the comparison of the vld OPCode output of both scripts, it gets clear where the better performance for yield from comes from.

screenshot 2018-11-07 at 21 29 55

screenshot 2018-11-07 at 21 30 15

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.