Backend Development 4 min read

Comparing Java's for(;;) and while(true) Loops and Their Generated Bytecode

The article explains the historical origin of Java's for(;;) loop, compares it with while(true) in terms of readability and bytecode generation, and shows that both constructs compile to identical bytecode in the standard javac compiler, making performance differences negligible.

Top Architect
Top Architect
Top Architect
Comparing Java's for(;;) and while(true) Loops and Their Generated Bytecode

The author discusses why many Java developers use for(;;) as an infinite loop, tracing its roots to C language syntax and noting that it avoids the magic constant 1 used in while(1) . Both forms are functionally equivalent, and personal preference often dictates which is chosen.

In Java, the author prefers while(true) but acknowledges that for(;;) is also common in projects. The article then examines whether there is any efficiency difference between the two constructs.

Using the Oracle/Sun JDK 8u (OpenJDK 8u) compiler, the following source snippets were compiled:

public void foo() {
    int i = 0;
    while (true) { i++; }
}
public void bar() {
    int i = 0;
    for (;;) { i++; }
}

The resulting bytecode for both methods is identical:

stack=1, locals=2, args_size=1
   0: iconst_0
   1: istore_1
   2: iinc          1, 1
   5: goto          2

Since the standard javac performs only minimal optimizations (constant folding and a few others), it generates the same bytecode for both loop forms. Consequently, any performance difference would have to arise later during interpretation or JIT compilation, where the input bytecode is identical.

Overall, the article concludes that the choice between for(;;) and while(true) is a matter of coding style rather than efficiency.

JavaPerformancebytecodeloopsfor loopwhile loop
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.