Skip to content

Comment on Which is faster? while(1) {} or while(2) {}

Comments

While not directly pertaining to the question, there are precedents for languages to special-case some inputs to loops for various reasons. Specifically, I'm thinking of Java here. Note the following code:

        int x;
        while (true) {
            x = 8;
            break;
        }
        System.out.println(x);
This code compiles and runs. Java is smart enough to statically prove that the loop condition is true, and so it guarantees that `x` will always be initialized.

Instead of `true`, you can also use things like `1==1` in the condition to the same effect. However, if you attempt the following:

        int x;
        boolean y = true;
        while (y) {
            x = 8;
            break;
        }
        System.out.println(x);
...the compiler will spit an error at you:
        While.java:9: error: variable x might not have been initialized
                System.out.println(x);
                                   ^
From a language design perspective, it's interesting to note this sort of demand and support for infinite loops in the language specification. One alternative to special-casing `while (true)` as shown above is to have an entirely separate construct for "I want this loop to be infinite", such as the `loop` keyword in Rust, or the bare `for` in Go. Alternatively, see how style guides for C-like languages tend to prefer `for (;;)` over `while (1)` to denote deliberately-infinite loops, to make the intent as obvious as possible.
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.