Skip to content

Instantly share code, notes, and snippets.

@hehachris
Created December 24, 2014 10:18
Show Gist options
  • Save hehachris/4c2d3078c4dc24172682 to your computer and use it in GitHub Desktop.
Save hehachris/4c2d3078c4dc24172682 to your computer and use it in GitHub Desktop.
PHP 5.5+: Array vs Generator
<?php
function xrange($start, $end)
{
$array = [];
for ($i = $start; $i <= $end; $i++) {
$array[] = $i;
}
return $array;
}
$max = isset($argv[1]) ? (int) $argv[1] : 1000000;
$items = xrange(1, $max);
echo "1: " . memory_get_usage() . "\n";
foreach ($items as $val) {
}
echo "2: " . memory_get_usage() . "\n";
<?php
function xrange($start, $end)
{
for ($i = $start; $i <= $end; $i++) {
yield $i;
}
}
$max = isset($argv[1]) ? (int) $argv[1] : 1000000;
$items = xrange(1, $max);
echo "1: " . memory_get_usage() . "\n";
foreach ($items as $val) {
}
echo "2: " . memory_get_usage() . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment