What is the difference between a standard while(true)
loop and for(;;)
?
Is there any, or will both be mapped to the same bytecode after compiling?
while(condition == true) will be true while condition is true . You can make that false by setting condition = false .
It may be little speed difference . For the case when the loop condition is not satisfied at the beginning, a do-while will always be slower than a for or a while due to the extra unnecessary iteration before checking the condition, but if you are doing this most likely the code is badly designed.
while (true) is not inherently bad practice. Certain uses of while (true) are bad practice, mostly busy-waits where other kinds of waits would be more appropriate, but there's nothing wrong with while (true) itself.
It distinguishes 1 and True in exactly the same way that the + example does. It's emitting a LOAD_GLOBAL (True) for each True , and there's nothing the optimizer can do with a global. So, while distinguishes 1 and True for the exact same reason that + does.
Semantically, they're completely equivalent. It's a matter of taste, but I think while(true)
looks cleaner, and is easier to read and understand at first glance. In Java neither of them causes compiler warnings.
At the bytecode level, it might depend on the compiler and the level of optimizations, but in principle the code emitted should be the same.
EDIT:
On my compiler, using the Bytecode Outline plugin,the bytecode for for(;;){}
looks like this:
L0 LINENUMBER 6 L0 FRAME SAME GOTO L0
And the bytecode for while(true){}
looks like this:
L0 LINENUMBER 6 L0 FRAME SAME GOTO L0
So yes, at least for me, they're identical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With