I heard someone once say that compilers frequently move the loop conditions to the bottom of the loop. That is, loops like these:
while (condition) {
...
}
is changed to :
if (condition) {
do {
...
} while (condition);
}
regarding machine independent optimization, why is latter preferable?
Loops implemented with the test at the bottom (a do loop) are called bottom-driven loops. ... Bottom-driven Loop. The loop must be initialized correctly. The ending condition must be tested correctly.
Answer: While loop checks the condition on top .
In a do-while loop, we are entering the body of the loop without checking any condition, so in this loop, the code in the body of the loop will execute at least once and then a boolean condition (either true or false) is checked that is passed as an argument in the while() function at the bottom of the loop.
The while loop is known as a pretest loop, because it tests the boolean expression before it executes the statements in its body.
Without compiler optimisation, the first loop goes to assembly code like this:
@@:
cmp ... ; or test ...
jz @f
...
jmp @b
Whereas the second loop goes to something like this:
jmp bottom
@@:
...
bottom:
cmp ... ; or test ...
jz @b
Conditional jumps are usually predicted to be taken so the first method could potentially lead to more pipeline/instruction cache flushes.
However, the most important thing is that for the first loop, there are two branches available per loop iteration (2N
), whereas in the second, each loop iteration only has one branch with a fixed overhead of the first unconditional jump (N+1
).
For more information on loop optimisation, see page 88 of this assembly optimisation guide.
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