Skip to content

Instantly share code, notes, and snippets.

@xintron
Created August 16, 2013 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xintron/6248907 to your computer and use it in GitHub Desktop.
Save xintron/6248907 to your computer and use it in GitHub Desktop.
Example showing how inefficient foreach + range are together (thanks to PHP returning the full array instead of doing it like e.g. python which is yielding the current number when looping over a range). Setting range to 1000000 will exhaust 128MB memory in PHP while the for loop has no such limit.
<?php
$s = microtime(true);
$c = 0;
foreach(range(1, 100000) as $i) {
$c++;
}
$e = microtime(true);
printf("Foreach :: Time: %f, count: %d\n", $e-$s, $c);
$s = microtime(true);
$c = 0;
for ($i = 0; $i < 100000; $i++) {
$c++;
}
$e = microtime(true);
printf("For :: Time: %f, count: %d", $e-$s, $c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment