6

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++) ;
    }

Does it cause halting some time or it will be omitted by JVM optimization?

Jama A.
  • 15,680
  • 10
  • 55
  • 88

4 Answers4

5

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?

Community
  • 1
  • 1
Gaurav
  • 1,549
  • 2
  • 15
  • 31
2

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.

Joe
  • 46,419
  • 33
  • 155
  • 245
  • Could you back it up with some documentation? By "optimised", do you mean "deleted"? It would seem strange that compiler omits some piece of code. – ŁukaszBachman Jan 11 '12 at 10:06
  • @ŁukaszBachman The optimal case is omitting that code and setting i 20000. – holgac Jan 11 '12 at 10:11
  • Not even that, because `i` is scoped to the loop! – Joe Jan 11 '12 at 10:13
  • @ŁukaszBachman it's called loop unrolling. See here: http://java.sun.com/products/hotspot/whitepaper.html – Joe Jan 11 '12 at 10:15
1

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.

holgac
  • 1,509
  • 1
  • 13
  • 25
  • javac hasn't done, doesn't do and never will do any kind of interesting optimizations. And the link shows one of the dial-your-score tests. Independent of how large you set the counter value you'll get the same result: You run the loop ~10k times in the interpreter, JIT kicks in and removes rest of loop independent of how large. Although in that case it seems to be the intended result. – Voo Jan 11 '12 at 10:31
0

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

shift66
  • 11,760
  • 13
  • 50
  • 83