Skip to content

Instantly share code, notes, and snippets.

@kkreft
Forked from hollodotme/generatorForEach.php
Created November 8, 2018 08:31
Show Gist options
  • Save kkreft/e803171c81237e2e539170ca11e274d6 to your computer and use it in GitHub Desktop.
Save kkreft/e803171c81237e2e539170ca11e274d6 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";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment