Skip to content

Instantly share code, notes, and snippets.

@jeffreysbrother
Last active March 11, 2020 10:22
Show Gist options
  • Save jeffreysbrother/b79b77af7b597029839c038830a478b0 to your computer and use it in GitHub Desktop.
Save jeffreysbrother/b79b77af7b597029839c038830a478b0 to your computer and use it in GitHub Desktop.
Generators in PHP
<?php
$start_time = microtime(true);
$startMemoryUsage = memory_get_peak_usage();
/**********************************************
WITHOUT GENERATOR
**********************************************/
$array = [];
function getData() {
for ($i = 0; $i < 999999; $i++) {
$array[] = $i;
}
return $array;
}
foreach (getData() as $data) {
echo $data;
}
/**********************************************
WITH GENERATOR
**********************************************/
// function getData() {
// for ($i = 0; $i < 999999; $i++) {
// yield $i;
// }
// }
// foreach(getData() as $data) {
// echo $data;
// }
/**********************************************
DO NOT COMMENT OUT CODE BELOW
**********************************************/
$end_time = microtime(true);
$endMemoryUsage = memory_get_peak_usage();
echo PHP_EOL;
echo 'total execution time: ' . bcsub($end_time, $start_time, 4) . ' seconds' . PHP_EOL;
echo 'bytes used: ' . number_format($endMemoryUsage - $startMemoryUsage) . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment