Skip to content

Instantly share code, notes, and snippets.

@caironm
Created October 5, 2019 05:41
Show Gist options
  • Save caironm/c17d7d9c149b56a83479335663e1dbd8 to your computer and use it in GitHub Desktop.
Save caironm/c17d7d9c149b56a83479335663e1dbd8 to your computer and use it in GitHub Desktop.
Generator
<?php
function xrange($start, $limit, $step = 1) {
if ($start < $limit) {
if ($step <= 0) {
throw new LogicException('O passo deve ser positivo');
}
for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new LogicException('O passo deve ser negativo');
}
for ($i = $start; $i >= $limit; $i += $step) {
yield $i;
}
}
}
echo 'Este exemplo implementa o antigo range(): ';
foreach (range(1, 9, 2) as $number) {
echo "$number ";
}
echo "\n";
echo 'Este exemplo implementa um range criado com generator: ';
foreach (xrange(1, 9, 2) as $number) {
echo "$number ";
}
/*
Este exemplo implementa o antigo range(): 1 3 5 7 9
Este exemplo implementa um range criado com generator: 1 3 5 7 9
Mesmo exemplo, resultados diferentes
-----------------------------------
| tempo | memoria, mb |
-----------------------------------
| sem gen | 0.7589 | 146.75 |
|----------------------------------
| com gen | 0.7469 | 8.75 |
|----------------------------------
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment