Comparing a while loop against a foreach loop of an array

Published on Sep 12, 2012 by Jamie Munro

Are you confused by the title?  I was when I first got the idea to even write this blog as well.  I was recently perusing the CakePHP change logs and came across an interesting commit – Optimization for Hash Method.

The optimization is quite simple, this code:


while (($key = array_shift($parts)) !== null)


Is replaced with the following code:


foreach ($parts as $key)


This is actually done several times in the commit.  It seems that the original developer is really keen on using the array_shift function.  Just in seeing this code, I thought the original code was odd to utilize that function so I immediately had to do a comparison and validate the optimization!


 To start we need two basic files.  The first file will test using a while loop:


<?php
$start = microtime();
$array = array_fill(0, 100, 'dummy_data');

while ($key = array_shift($array) !== null) {
echo $key;
}

$end = microtime();
?>
<hr/>
Execution Time: <?php echo ($end - $start) ;?> seconds.


The second file needs to then use a foreach  loop:


<?php
$start = microtime();
$array = array_fill(0, 100, 'dummy_data');

foreach ($array as $key) {
echo $key;
}

$end = microtime();
?>
<hr/>
Execution Time: <?php echo ($end - $start) ;?> seconds.


Now that the basics are done, it's time to pull out the recent A Simple But Effective Speed Comparison tool that I built earlier and running the comparison between the two files.

The results are a bit surprising, the while loop code executed about 6,000 times in 10 seconds.  Whereas the foreach loop code executed about 8,000 times in 10 seconds.  This equates to about a 25% improvement while looping through an array of 100 records.

I actually thought that using array_shift and assigning the results to a value, then checking that it is not null would be much slower compared to a foreach loop than just 25%.  It seems like it would have been much slower and in reality if the array was smaller it would be even more negligible of a difference.

At the end of the day, I think the foreach loop is more readable and would continue to use that regardless of the 25% speed increase…

Tags: Optimization | foreach | while | PHP

Related Posts

blog comments powered by Disqus