A loop with an empty body in Java

前端 未结 4 1778
时光说笑
时光说笑 2021-01-18 06:53

During bug fixing in very old project I\'ve faced with strange method, it looks like this:

   void waiter() {
        for (int i = 0; i < 20000; i++) ;
           


        
相关标签:
4条回答
  • It may be optimised, it may not. Depends on the level of optimisation in the compiler.

    The variable i is scoped to the loop, so it will not be available after. The compiler is able to identify statically that the loop will run a known number of times. It also knows that the empty statement is repeated this many times. It can then transform a number of empty statements into one empty statement, or no statement at all. This has the effect of removing the code altogether from the abstract syntax tree.

    This will happen under some optimisation settings and compilers, and not under others.

    0 讨论(0)
  • 2021-01-18 07:23

    I don't know if it has changed, I haven't used java for 2 years but it doesn't seem to.

    http://www.herongyang.com/JVM/Benchmark-Int-Empty-Loop-16-Nanosecond.html http://www.herongyang.com/JVM/Benchmark-Long-Empty-Loop-25-Nanosecond.html

    This test also confirms that the Java bytecode compiler "javac" is not doing any optimization to replacing the empty loop with "i=steps" which is the net effect of the loop.

    0 讨论(0)
  • 2021-01-18 07:23

    Yes, it will be optimised.I've tried :D

    0 讨论(0)
  • 2021-01-18 07:34

    It will be optimized after few runs by JIT. The JVM , at the first run, needs to check if the value if i that is being incremented is not being used anywhere.

    Check this article as well :

    Java: how much time does an empty loop use?

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