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 com
JVM will find the best way to make bytecode and in both cases should do the same.So I think there's no difference. while(true) is just prettier.
I have looked at the generated byte code and found that since the condition is always true (at compile time), the compiler will compile away the test and just branch always back to the top of the loop. I assume that a continue statement will also do a branch always back to the top of the loop. So, not only does it not make any difference, there isn't even any code generated to test anything.
Functionally there is no difference. Any efficiency gained or lost by a difference in bytecode will likely be insignificant compared to any instruction you would run in the body of the loop.
Depending upon the compiler, it should map to the same byte code.
It's up to you which one to use. Cause they are equals to compiler.
create file:
// first test
public class Test {
public static void main(String[] args) {
while (true) {
System.out.println("Hi");
}
}
}
compile:
javac -g:none Test.java
rename Test.class Test1.class
create file:
// second test
public class Test {
public static void main(String[] args) {
for (;;) {
System.out.println("Hi");
}
}
}
compile:
javac -g:none Test.java
mv Test.class Test2.class
compare:
diff -s Test1.class Test2.class
Files Test1.class and Test2.class are identical
On Oracle Java 7 you get the same byte code. You cannot tell from the byte code which was using in the original. Which is best is a matter of taste. I use while(true)