I was told that a while loop was more efficient than a for loop. (c/c++) This seemed reasonable but I wanted to find a way to prove or disprove it.
I have tried three tests using analogous snippets of code. Each containing Nothing but a for or while loop with the same output:
Should I have tried anything else, or can anyone confirm one way or the other?
In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.
Among these 3 versions of loops which one is faster… their semantic is equivalent. if your compiler is smart enough, the cpu instructions generated are exactly the same. so none of them is faster than the other.
A while loop is a little easier to explain than a for loop because a while loop will simply run the same code over and over until the condition becomes false. Let's take a look at a simple example of a while loop!
Usually pre-increment / pre-decrement is faster than post-increment/post-decrement, because post-<> require to save a temporal value for returning.
While loop is a loop statement used for the repeated execution of the statements. It is preferred when the loop statement is required and a number of iterations are not defined. In case the condition is not known, it shows an error unlike for loop which will have infinite iterations.
All loops follow the same template:
{
// Initialize
LOOP:
if(!(/* Condition */) ) {
goto END
}
// Loop body
// Loop increment/decrement
goto LOOP
}
END:
Therefor the two loops are the same:
// A
for(int i=0; i<10; i++) {
// Do stuff
}
// B
int i=0;
while(i < 10) {
// Do stuff
i++;
}
// Or even
int i=0;
while(true) {
if(!(i < 10) ) {
break;
}
// Do stuff
i++;
}
Both are converted to something similar to:
{
int i=0;
LOOP:
if(!(i < 10) ) {
goto END
}
// Do stuff
i++;
goto LOOP
}
END:
Unused/unreachable code will be removed from the final executable/library.
Do-while loops skip the first conditional check and are left as an exercise for the reader. :)
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