PHP for() VS foreach() benchmark
Got curious what the performance difference between using for() and foreach() was on an array of elements in PHP. So, coded up a quick test.
GitHub Gist
https://gist.github.com/3909074/628478c74d736854f4499fa3383eb97e5db84b6f
<?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";
?>
The result in PHP 5.3.15 with Suhosin-Patch (cli) (built: Aug 24 2012 17:45:44) on a MacBook Pro.
For took: 1.612ms
Foreach took: 0.602ms
Here is the result in PHP 5.4.7 (cli) (built: Sep 17 2012 21:16:51) on a virtual machine in SoftLayer with two CPUs and 1GB of RAM.
For took: 1.836ms
Foreach took: 0.543ms
--- UPDATE ---
Here is an updated GitHub Gist which also includes the time to execute for() without calling count() on each iteration. It is the fastest of all three methods.
Written by Justin Keller
Related protips
5 Responses
Why are you counting elements in an array before every iteration?
Shouldn't it be a better solution?
$elementscount = count($elements);
for($i = 0; $i < $elementscount; $i++) { }
I can be almost sure that now the results will be slightly different!
Sorry, didn't spot the update at the bottom ;)
U suck. Don't use count() func in every iteration, noob!
Then For fastest Foreach; Just use count() before for!
@sergeyaleynicov Way to be a douche.
If u can just use count() before for! Then For fastest Foreach hahaha. core wrong !