PHP: FOR vs WHILE

Published:
Updated:
The age old debate of FOR vs WHILE has raged on for years and has had numerous people arguing for both types of loop. Programmers striving to make their code as efficient and fast as possible have been trying to answer this question and there have numerous varying results. Now you can see for yourself.The FOR loop is probably the tidier and more professional looking of the two.
      for($x = 0; $x <= 100; $x++){
      }
?>
Easy and simple to understand.

The code we will be using to benchmark this loop is as follows:
      $start = microtime(true);
      for($x = 0; $x <= 5000000; $x++){
      }
      $end = microtime(true);
      $time = $end - $start;
      echo "FOR loop:" . $time . " seconds";
?>="3" title="The WHILE loop">The WHILE loop is has 2 extra lines of code to initialise the index variable and increment it. The FOR loop incorporates these into it's syntax.
      $x = 0;
      while($x <= 100){
            $x++;
      }
?>
Ever so slightly more complex but it's essentially the same items organised a different way.

The code we will be using to benchmark this loop is as follows:
      $start = microtime(true);
      $x = 0;
      while($x <= 5000000){
            $x++;
      }
      $end = microtime(true);
      $time = $end - $start;
      echo "WHILE loop:" . $time . " seconds";
?>="4" title="The Results">This is what it all comes down to, the results. The following is the complete benchmarking script used for this line of testing.

      // Start FOR test
      $start = microtime(true);
      for($x = 0; $x <= 5000000; $x++){
      }
      $end = microtime(true);
      $time = $end - $start;
      echo "FOR loop:" . $time . " seconds";
      // End FOR test
      
      echo "";
      
      // Start WHILE test
      $start = microtime(true);
      $x = 0;
      while($x <= 5000000){
            $x++;
      }
      $end = microtime(true);
      $time = $end - $start;
      echo "WHILE loop:" . $time . " seconds";
      // End WHILE test
?>Upon executing this script, the results were as follows:
FOR loop:
0.69475388526917 seconds
WHILE loop:
0.60405921936035 seconds
You will notice that, in this test, WHILE appears to be the more efficient loop. There are arguments for and against this (see the links in the references below).

The results do vary, however, WHILE always seems to come out faster. See what you think!http://myphpdigest.com/news.php?title=PHP_Benchmark_-_For_vs_While
http://mgccl.com/2007/03/26/break-the-for-vs-while-loop-war
http://cosminb.blogspot.com/2004/09/performance-tweaking-for-vs-while-vs.htmlstep>
4
6,392 Views

Comments (7)

CERTIFIED EXPERT

Commented:
What happens when the part of the source related to "for" is switched with souce of "while" test? I do not know how the source in PHP is compiled and optimized. Does it make a difference?

Also, in C or C++ it is recommended to prefer ++i, not the i++. The reason is that i++ increments the contend and returns the original value. This means that there must be another hidden variable and the assignment of the old content to it. What is the time when you do ++$x (I do not know PHP and do not know whether it is possible at all).
CERTIFIED EXPERT

Commented:
... also the $start, $end, and $time variables already existed in the second case. Could not that distort the results?


A side note. The truth is that the C-like for is only a syntactically nicer while with the important parts put together, to the opening part of the loop. On the other hand, new languages tend to give the for-loop slighly more general (and more mathematical) meaning "for each element in the container". In other words, the semantics based on existence of iterators more than on existence of a counter. In such case the syntax of the for-loop becames both syntactically simpler (element identifier plus container identifier, the iterator may be hidden) and sematically richer (explicitly said what container is iterated and what is the variable representing the element). And also, such for loop may say less about the order of processing (the potentials for future parallel processing).

From that point of view, the for-loop tends to be more abstract (hence more readable and more understandable) than the while-loop.
Most Valuable Expert 2011
Author of the Year 2014

Commented:
A great use for WHILE: iterate over the results set from a query.


while ($row = mysql_fetch_assoc($resource)
{
    /* PROCESS QUERY ROW */
}
Richard QuadlingSenior Software Developer

Commented:
Many many years ago, I was taught that a for() loop traditionally for finite loops whereas a while() is for potentially infinite loops with an escape mechanism.

PHP also has foreach() (similar to other languages "for var in collection"). This allows you to iterate a finite set without knowing the limits; e.g.

<?php
foreach($some_array as $key => $value) {
 // Process key and / or value
}
?>

As you move from simpler coding to more complex OOP coding, pattern reuse, etc., then you will find PHP provides some really useful iterators built in : http://docs.php.net/manual/en/spl.iterators.php

These can be extended to provide a uniform and consistent mechanism to access "collections" (arrays, directories, etc.) ; e.g.

<?php
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/some/path')) as $object_File) {
 // Process a file from within the structure starting at /some/path.
}
?>





CERTIFIED EXPERT
Top Expert 2006

Commented:
Although this kind of coding issues have a performance impact, more important is the code inside the loop.

If you can improve 0.01ms by optimizing the inners of the loop, you will benefit more from it, than changing from for's to whiles.

Also, function caching and page caching etc have better impact on your overal performance, because you just skip out on the whole loop.

When you look at the structure of loops, it is also more efficient to compare against zero, than to a high number; ie loop A will be slower than loop B
A: for($i = 0; $i < 100; $i++)
B: for($i = 100; $i > 0; $i--)

Although this is a nice article, the actual performance gain is minimal for this type of optimizations.

kind regards

Arnoud

View More

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.

Get access with a 7-day free trial.
You Belong in the World's Smartest IT Community