Created
October 17, 2012 23:53
-
-
Save nodesocket/3909074 to your computer and use it in GitHub Desktop.
Benchmark of for vs foreach 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 | |
$elements = array(); | |
//// | |
// An array of 10,000 elements with random string values | |
//// | |
for($i = 0; $i < 10000; $i++) { | |
$elements[] = (string)rand(10000000, 99999999); | |
} | |
$time_start = microtime(true); | |
//// | |
// for test | |
//// | |
for($i = 0; $i < count($elements); $i++) { } | |
$time_end = microtime(true); | |
$for_time = $time_end - $time_start; | |
$time_start = microtime(true); | |
//// | |
// foreach test | |
//// | |
foreach($elements as $element) { } | |
$time_end = microtime(true); | |
$foreach_time = $time_end - $time_start; | |
echo "For took: " . number_format($for_time * 1000, 3) . "ms\n"; | |
echo "Foreach took: " . number_format($foreach_time * 1000, 3) . "ms\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can add "foreach($elements as $key => $element) { }" as well. It'll be the worst one.