Skip to content

Instantly share code, notes, and snippets.

@jeffreysbrother jeffreysbrother/index.php
Last active Jun 12, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.