Java: for(;;) vs. while(true)

后端 未结 9 1888
予麋鹿
予麋鹿 2020-12-01 15:29

What is the difference between a standard while(true) loop and for(;;)?

Is there any, or will both be mapped to the same bytecode after com

相关标签:
9条回答
  • 2020-12-01 15:55

    JVM will find the best way to make bytecode and in both cases should do the same.So I think there's no difference. while(true) is just prettier.

    0 讨论(0)
  • 2020-12-01 15:55

    I have looked at the generated byte code and found that since the condition is always true (at compile time), the compiler will compile away the test and just branch always back to the top of the loop. I assume that a continue statement will also do a branch always back to the top of the loop. So, not only does it not make any difference, there isn't even any code generated to test anything.

    0 讨论(0)
  • 2020-12-01 16:03

    Functionally there is no difference. Any efficiency gained or lost by a difference in bytecode will likely be insignificant compared to any instruction you would run in the body of the loop.

    0 讨论(0)
  • 2020-12-01 16:09

    Depending upon the compiler, it should map to the same byte code.

    0 讨论(0)
  • 2020-12-01 16:10

    It's up to you which one to use. Cause they are equals to compiler.

    create file:

    // first test
    public class Test {
        public static void main(String[] args) {
            while (true) {
                System.out.println("Hi");
            }
        }
    }
    

    compile:

    javac -g:none Test.java
    rename Test.class Test1.class
    

    create file:

    // second test
    public class Test {
        public static void main(String[] args) {
            for (;;) {
                System.out.println("Hi");
            }
        }
    }
    

    compile:

    javac -g:none Test.java
    mv Test.class Test2.class
    

    compare:

    diff -s Test1.class Test2.class
    Files Test1.class and Test2.class are identical
    
    0 讨论(0)
  • 2020-12-01 16:11

    On Oracle Java 7 you get the same byte code. You cannot tell from the byte code which was using in the original. Which is best is a matter of taste. I use while(true)

    0 讨论(0)
提交回复
热议问题