<

PHP: FOR vs WHILE

Published on
9,567 Points
6,167 Views
4 Endorsements
Last Modified:
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
Comment
Author:cr4ck3rj4ck
7 Comments
 
LVL 7

Expert Comment

by:DarkHill
Very interesting, for easier readability and simplicity I'd still stick to "for", though.
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
great , looks nice
0
 
LVL 29

Expert Comment

by:pepr
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).
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
LVL 29

Expert Comment

by:pepr
... 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.
0
 
LVL 111

Expert Comment

by:Ray Paseur
A great use for WHILE: iterate over the results set from a query.


while ($row = mysql_fetch_assoc($resource)
{
    /* PROCESS QUERY ROW */
}
0
 
LVL 40

Expert Comment

by:Richard Quadling
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.
}
?>





0
 
LVL 49

Expert Comment

by:Roonaan
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
0

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Join & Write a Comment

The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month