Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Loop or While Loop - Efficiency

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?

like image 567
jwegner Avatar asked Nov 18 '10 18:11

jwegner


2 Answers

I think you're drawing the wrong conclusion from the advice you've been given.

The reason (in this instance at least) to prefer the for construct over the while has nothing to do with efficiency; it's all about writing code that expresses your intentions in a clear and easy to understand manner.

The for places the initial condition, increment, and exit condition all in one place, making it easier to understand. The while loop spreads them around. For example, in your sample, what is the initial value of i? -oh, you forgot to specify it? --that's the point.

like image 50
David Gelhar Avatar answered Sep 22 '22 01:09

David Gelhar


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

like image 32
Heinzi Avatar answered Sep 23 '22 01:09

Heinzi