Comparison of while(true) and for(;;) Infinite Loops in Java
This article examines the differences between while(true) and for(;;) infinite loops in Java, presenting equivalent code examples, compiling them to bytecode, and showing that both constructs compile to identical bytecode using a goto instruction, concluding there is no performance distinction.
This article analyzes the two common ways to write an infinite loop in Java— while(true) and for(;;) —and investigates whether there is any functional or performance difference between them.
Example using for(;;) :
public class HollisTest {
public static void main(String[] args) {
for(;;){
System.out.println("this is hollis testing....");
}
}
}Example using while(true) :
public class HollisTest {
public static void main(String[] args) {
while(true){
System.out.println("this is hollis testing....");
}
}
}Both files are compiled with the standard Java compiler:
javac HollisTest.javaThe resulting .class files are then decompiled with javap , revealing that the bytecode for the two versions is identical. The key part of the bytecode shows a goto instruction that creates the infinite loop:
public class HollisTest {
public HollisTest();
public static void main(java.lang.String[]);
Code:
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3 // String this is hollis testing....
5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: goto 0
}The analysis demonstrates that both constructs compile to the same bytecode and therefore have no performance difference; the choice between them is purely stylistic, with some developers preferring while(true) for clarity and others preferring for(;;) to avoid IDE warnings.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.