Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any performance difference between for() and while()?

Tags:

Or is it all about semantics?

like image 209
sharkin Avatar asked May 11 '09 12:05

sharkin


People also ask

Which is faster while or for?

Efficiency, and While vs For Using for: % Time elapsed: 0.0010001659 seconds. Using while: % Time elapsed: 0.026000023 seconds. The main reason that While is much slower is because the while loop checks the condition after each iteration, so if you are going to write this code, just use a for loop instead.

Which is better for or while loop?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.

What is the difference between a for () and while loop ()?

The major difference between for loop and while loop is that for loop is used when the number of iterations is known whereas, in the while loop, execution is done until the statement in the program is proved wrong.

Which is faster while or for loop Python?

Also, the execution speed varies significantly between the fastest contestant and the looser while loop: for-each loops are more than six times faster than while loops. Even the for-range loop is nearly two times faster than the while loop. Now, stop for a moment and think about which loop you use the most.


1 Answers

Short answer: no, they are exactly the same.

Guess it could in theory depend on the compiler; a really broken one might do something slightly different but I'd be surprised.

Just for fun here are two variants that compile down to exactly the same assembly code for me using x86 gcc version 4.3.3 as shipped with Ubuntu. You can check the assembly produced on the final binary with objdump on linux.

int main()
{
#if 1
    int i = 10;
    do { printf("%d\n", i); } while(--i);
#else
    int i = 10;
    for (; i; --i) printf("%d\n", i);
#endif
}

EDIT: Here is an "oranges with oranges" while loop example that also compiles down to the same thing:

    while(i) { printf("%d\n", i); --i; }
like image 56
akent Avatar answered Sep 30 '22 22:09

akent