Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why bottom test loop is preferable?

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?

like image 584
JohnTortugo Avatar asked Mar 20 '12 00:03

JohnTortugo


People also ask

What is a bottom tested loop?

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.

Which loop checks the condition on top or bottom?

Answer: While loop checks the condition on top .

Do While loop check the condition at the bottom of the loop?

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.

Which loops are pretest loops?

 The while loop is known as a pretest loop, because it tests the boolean expression before it executes the statements in its body.


1 Answers

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.

like image 68
Mike Kwan Avatar answered Sep 28 '22 09:09

Mike Kwan