<

PHP: FOR vs WHILE

Published on
9,693 Points
6,293 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
Author:cr4ck3rj4ck
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Get 7 days free