[dev] For vs. Foreach

Ronan SALMON rsalmon at mbpgroup.com
Wed Feb 3 10:20:58 UTC 2010


> commit 560d9d8ba41200dec93b839449b983ac8f61d49e
> Author: Michael M Slusarz <slusarz at curecanti.org>
> Date:   Mon Feb 1 15:46:18 2010 -0700
>
>    Just kidding - array_merge() is terrible slow
>
> framework/Imap_Client/lib/Horde/Imap/Client/Utils.php |    4 +++-
> 1 files changed, 3 insertions(+), 1 deletions(-)

Hi all,

I always thought 'foreach' was faster than 'for' when dealing with  
arrays. So I ran the following script on my machine (thanks to  
http://derekgallo.com/2007/04/19/for-vs-foreach/) :

set_time_limit(0);
$array = array();
echo "Filling array\n";
function microtime_float()
{
     list($usec, $sec) = explode(" ", microtime());
     return ((float)$usec + (float)$sec);
}

for($index=0; $index < 100000; $index++) {
	$array[$index] = $index;
}

$start = microtime_float();
$ids = array();
for($iteration = 0;$iteration < 5; $iteration++) {
	for($index=0;$index < count($array);$index++) {
		$ids[] = $array[$index];;
	}
}
$end = microtime_float();
$duration = $end - $start;
echo "For loop with count : $duration \n";

$start = microtime_float();
$ids = array();
for($iteration = 0;$iteration < 5; $iteration++) {
	$y = count($array);
	for($index=0;$index < $y;$index++) {
		$ids[] = $array[$index];;
	}
}
$end = microtime_float();
$duration = $end - $start;
echo "For loop without count : $duration \n";

$start = microtime_float();
$ids = array();
for($iteration=0; $iteration < 5; $iteration++)	{
	foreach ($array as $value_data)	{
		$ids[] = $value_data;
	}
}
$end = microtime_float();
$duration = $end - $start;
echo "Foreach loop: $duration \n";

Results with php-5.2.11 :
Filling array
For loop with count : 0.47997808456421
For loop without count : 0.31830286979675
Foreach loop: 0.2723331451416

Obviously, with tiny little arrays, you probably won't see the  
difference, but it shows that if you use 'for' loops, you shouldn't  
put count() within the loop declaration.


Hope this helps,
Ronan.


More information about the dev mailing list