Why Does Java’s for(;;) Loop Exist and Is It Faster Than while(true)?
An exploration of Java’s infinite loop constructs reveals that for(;;) originates from C, offers a concise syntax without magic numbers, and, according to bytecode analysis of JDK8u, performs identically to while(true), with performance determined solely by the JVM implementation.
Searching the JDK8u source tree shows roughly the same number of infinite loops written as for(;;) and while(true) (369 vs 323 occurrences).
The for(;;) syntax in Java traces back to C, where developers used it to avoid writing a literal constant such as while(1). It provides a clear way to express an infinite loop without a “magic number”.
In C, without including certain headers, there is no built‑in bool type, so while(1) was common, but many preferred for(;;) for readability.
In Java the author prefers while(true), though for(;;) is also acceptable.
Which is faster in Java, for(;;) or while(true) ?
The Java language specification does not dictate performance; it depends on the implementation. Compiling both versions with javac (Oracle/Sun JDK8u / OpenJDK8u) yields identical bytecode, as shown below.
public void foo() {
int i = 0;
while (true) { i++; }
}
/* Bytecode:
0: iconst_0
1: istore_1
2: iinc 1, 1
5: goto 2
*/ public void bar() {
int i = 0;
for (;;) { i++; }
}
/* Bytecode:
0: iconst_0
1: istore_1
2: iinc 1, 1
5: goto 2
*/Since the generated bytecode is identical, any performance difference would only arise later during interpretation or JIT compilation, where the input is the same, so the output is effectively identical.
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.
