-
-
Save kkreft/e803171c81237e2e539170ca11e274d6 to your computer and use it in GitHub Desktop.
Comparison of generator with foreach and yield from
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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