Skip to content

Instantly share code, notes, and snippets.

@wcomnisky
Created March 4, 2021 08:36
Show Gist options
  • Save wcomnisky/349c80094955320555d325475f24f143 to your computer and use it in GitHub Desktop.
Save wcomnisky/349c80094955320555d325475f24f143 to your computer and use it in GitHub Desktop.
PHP Yield (Generator)
<?php
ini_set('memory_limit', '4096M');
$timeStart = microtime(true);
$mem = memory_get_usage(true);
function arange($start, $end) {
$array = array();
for ($i = $start; $i <= $end; $i++) {
$array[] = $i;
}
return $array;
}
function yrange($start, $end) {
for ($i = $start; $i <= $end; $i++) {
yield $i;
}
}
$range = arange(1, 10000000);
foreach( $range as $num) {
if ($num % 2 != 0 || $num % 1000000 != 0) {
continue;
}
echo $num . PHP_EOL;
}
$memEnd = memory_get_usage(true);
$timeStop = microtime(true);
var_dump([
'memUsage:' => $memEnd - $mem,
'memPeak' => memory_get_peak_usage(true)/(1024**2),
'timeSpent' => $timeStop - $timeStart
]);
// Array
// array(3) {
// 'memUsage:' =>
// int(0)
// 'memPeak' =>
// double(514.00390625)
// 'timeSpent' =>
// double(16.428406953812)
// }
// Yield
// array(3) {
// 'memUsage:' =>
// int(0)
// 'memPeak' =>
// int(2)
// 'timeSpent' =>
// double(15.792601108551)
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment