A loop with an empty body in Java

前端 未结 4 1828
时光说笑
时光说笑 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条回答
  •  不要未来只要你来
    2021-01-18 07:23

    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.

提交回复
热议问题