Is for(;;) Faster Than while(true) in Java? A Bytecode Comparison
This article examines the origins of Java's infinite loop constructs, compares the frequency of for(;;) and while(true) in the JDK source, and shows through compiled bytecode that both forms are semantically identical and have no inherent performance advantage.
In JDK 8u source a quick grep shows 369 occurrences of for (;;) and 323 of while (true), indicating they are used similarly.
The for (;;) syntax originates from C, where programmers avoided writing the literal “1” in while (1). It expresses an infinite loop without a magic number.
In Java, both while (true) and for (;;) are semantically equivalent; the choice is often stylistic.
Compiling the two methods below with javac produces identical bytecode, confirming no performance difference at the compiler level.
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 identical to above */Since the generated bytecode is the same, any runtime performance difference would depend on later JIT optimizations, which also treat them equivalently.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
