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";
}