Last active
March 11, 2020 10:22
-
-
Save jeffreysbrother/b79b77af7b597029839c038830a478b0 to your computer and use it in GitHub Desktop.
Generators in PHP
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 | |
$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