+ 1

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

please tell me someone only if you're sure.

2nd Aug 2019, 7:45 AM
Rajnish Kush
Rajnish Kush - avatar
7 Respostas
+ 4
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).
2nd Aug 2019, 10:15 AM
DonPietro Cavastano
DonPietro Cavastano - avatar
+ 10
do-while is fastest to run the first iteration as there is no checking of a condition at the start.
2nd Aug 2019, 9:46 AM
Sonic
Sonic - avatar
+ 5
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.
2nd Aug 2019, 7:55 AM
Franky BrainBox
Franky BrainBox - avatar
+ 2
franky understood a lil bit, thanks
2nd Aug 2019, 8:00 AM
Rajnish Kush
Rajnish Kush - avatar
+ 2
Of course do-while because at least the first execution will go before the condition is check
4th Aug 2019, 5:52 AM
Al-Amin Rais
Al-Amin Rais - avatar
0
Mr. Bihar you are welcome. We are all here to learn new things for a better understanding.
2nd Aug 2019, 8:02 AM
Franky BrainBox
Franky BrainBox - avatar
0
For
17th Aug 2019, 6:47 AM
Paritosh Mishra