Alex Rivera | Logout

For Loop or While Loop - Efficiency

Asked 2010-11-18T18:21:40.703
10

This may be a stupid question, but how does the efficiency of a while loop compare to that of a for loop? I've always been taught that if you can use a for loop, then I should. But what actually is the difference between :

$i = 0;
while($i < 100) {
     echo $i;
     $i++;
} 

compare to:

for($i = 0; $i < 100; $i++) {
    echo $i;
}

I know in these specific examples the difference is like .000000001%, but when we are talking about large complex loops, what is the difference?

Edit
Report

2 Answers

4

That depends on the exact compiler that you use. In your example, a good compiler will create the same machine code for both options.

answered 2010-11-18T18:25:13.413
4

The performance difference between for loop and while loop is not a big issue because modern compilers can generate same machine code for both loops and secondly both loops require same operations:

  1. Initialization of counter variable.
  2. Test condition.
  3. Increment / decrement in counter variable.

In general you should use for loop in your code for the following reasons:

  1. To increase the readability of your code.
  2. To improve the maintainability of your code since all three major parts of a loop i.e. initialization, increment / decrement and test condition are written at the same line(in most cases).
  3. It limits the scope of counter variables better than a while loop, hence it helps in better memory management.

I hope that makes sense and would help.

answered 2012-09-27T12:40:23.993

Your Answer