Comparing a while loop against a foreach loop of an array Comparing a while loop against a foreach loop of an array

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…

Published on Sep 12, 2012

Tags: Optimization | foreach | while | PHP

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.