Skip to content

Instantly share code, notes, and snippets.

@hollodotme
Created November 7, 2018 19:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hollodotme/f6fed5920bdb8ecfa16936b8d0ad52a5 to your computer and use it in GitHub Desktop.
Save hollodotme/f6fed5920bdb8ecfa16936b8d0ad52a5 to your computer and use it in GitHub Desktop.
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
Copy link
Author

hollodotme 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
Copy link
Author

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