Which loop is fastest? while, do-while or for ? | SoloLearn: Learn to code for FREE!


Which loop is fastest? while, do-while or for ?

please tell me someone only if you're sure.

8/2/2019 7:45:35 AM

Robb 🔭

7 Answers

New Answer


do-while is fastest to run the first iteration as there is no checking of a condition at the start.


I don't think any is faster than the other but they have different purposes... while loop is mainly used when you don't know how many times your code will run for loop is used when you know the amount of time your code will run. do-while loop is used when you want your code to run at least once.


franky understood a lil bit, thanks


All loops at low-level are translated into same assembly instructions. These ones are changed at compile-time to known structs. CPU register ECX(or RCX in 64 bot architectures) is the initialization variable(i in for loops) while final check is done via Jxx instructions(jump instructions in assembly). An example: MOV ECX, 0x5 loop: INC EAX DEC ECX CMP ECX, ECX JNZ loop ... In this snippet of assembly code ECX(i) is initialized to 5 instead of 0(it is more convenient), EAX register is incremented and ECX is decremented by one. Then there is the check done via CMP that subtract the operands and if the result is not zero jump to loop label(function).



Mr. Bihar you are welcome. We are all here to learn new things for a better understanding.


Of course do-while because at least the first execution will go before the condition is check