Question

Some situation, we can use while loop or do-while loop interchangeably. One of my friend told me that such situation we should use do-while loop. Because it is faster than while. Can anyone give me proof for it?

Was it helpful?

Solution

Both loops are pretty much the same (except of the fact that a do-while is executed at least once), and in many cases compile to the same instructions, at least on x86.

The following code:

int main(int argv, char *argc[]) {
    int a = 0;
    while (a < 100) {
        a++;
    }
    a = 0;
    do {
        a++;
    }while(a < 100);
    return 0;
}

Generates this assembly (using gcc -S -o temp.as temp.c):

_main:
    pushl   %ebp
    movl    %esp, %ebp
    andl    $-16, %esp
    subl    $16, %esp
    call    ___main
    movl    $0, 12(%esp) >> while
    jmp L2  
L3:
    addl    $1, 12(%esp)
L2:
    cmpl    $99, 12(%esp)
    jle L3
    movl    $0, 12(%esp)  >> do-while
L4:
    addl    $1, 12(%esp) 
    cmpl    $99, 12(%esp)
    jle L4
    movl    $0, %eax
    leave
    ret

OTHER TIPS

You are comparing apples and peaches.

A do-while and while loops are different in what functionality they provide.
do-while always exectures once, while only executes if condition is true.

In situations where you can use either there is no performance difference.
And if you have a doubt then profiling it yourself on your platform or analysing the assembly output of both is what you should do.

No. The C standard does not provide requirements for execution speed, so it is impossible to prove in general.

The difference between while and do-while is that do-while always executes the first time, without checking the condition. So assuming that the condition is actually true the first time, do-while saves this one check of the condition.

This is a micro-optimization at best.

If you dont care about the different semantic (at least once vs. maybe none), there is no difference.

C semantic describes the behavior of an abstract machine in which issues of optimisation are irrelevant. (see C99 Standard, 5.1.2.3p1)

If it's a situation where the compiler can optimize it well, stick with the while loop. Top-of-loop testing is clearer. The reason is rooted in formal verification. The while loop tests the preconditions for the correct execution of the body. The do loop executes a body once without testing anything, and then has to deal with the aftermath, so to speak. It's more tricky to reason about. We have to think about what the situation is as a result of the conditions that existed before the loop plus the effect of the unguarded execution of the first iteration.

If you have a loop guard which is expensive (like a call to some external function that can do I/O or who knows what else) then think about moving it down, if possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top