Infinite Loops in Java: while(true) vs for(;;) – Which Is Better?
This article compares the two common ways to write infinite loops in Java—while(true) and for(;;)—exploring their origins, usage differences, and performance by examining JDK source counts and compiled bytecode, concluding they are functionally equivalent.
Sometimes we write loops that exit based on a condition rather than a fixed iteration count, leading to patterns like:
while (true)
for (;;)
The question arises: which form is better?
The discussion references a Zhihu answer that analyzes these two styles.
mymbp:/Users/me/workspace/jdk8u/jdk/src
$ egrep -nr "for \(\s?;\s?;" . | wc -l
369
mymbp:/Users/me/workspace/jdk8u/jdk/src
$ egrep -nr "while \(true" . | wc -l
323The counts show no significant difference.
The for (;;) style originates from C, where writing while(1) without a boolean literal was common; however, many developers dislike the magic number 1. Using for (;;) expresses an infinite loop without any condition or magic number, making it visually clear.
In Java, the author prefers while (true) but accepts for (;;) in other projects.
Regarding performance, the Java language specification does not dictate which is faster; it depends on the implementation. Examining the bytecode generated by javac for both forms in Oracle/Sun JDK8u shows they compile to identical bytecode.
public void foo() {
int i = 0;
while (true) { i++; }
}
/*
public void foo();
Code:
stack=1, locals=2, args_size=1
0: iconst_0
1: istore_1
2: iinc 1, 1
5: goto 2
*/ public void bar() {
int i = 0;
for (;;) { i++; }
}
/*
public void bar();
Code:
stack=1, locals=2, args_size=1
0: iconst_0
1: istore_1
2: iinc 1, 1
5: goto 2
*/Since both compile to the same bytecode, there is no performance difference at the source level; any further differences would depend on JIT compilation and runtime optimizations, which treat them identically.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
