Created
November 7, 2018 19:24
-
-
Save hollodotme/f6fed5920bdb8ecfa16936b8d0ad52a5 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
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