Created
August 16, 2013 10:42
-
-
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.
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 | |
$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