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?
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.
That depends on the exact compiler that you use. In your example, a good compiler will create the same machine code for both options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With