Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: for(;;) vs. while(true)

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?

like image 976
sjas Avatar asked Jan 16 '12 13:01

sjas


People also ask

What can I use instead of while true in Java?

while(condition == true) will be true while condition is true . You can make that false by setting condition = false .

Which is faster while or for Java?

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.

Is it good practice to use while true?

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.

Is while 1 the same as while true?

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.


1 Answers

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.

like image 64
Óscar López Avatar answered Oct 25 '22 17:10

Óscar López