Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A loop with an empty body in Java

Tags:

java

for-loop

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?

like image 601
Jama A. Avatar asked Jan 11 '12 09:01

Jama A.


People also ask

What is empty loop body in Java?

However, we could mean by "Empty body loop" a loop that has no side effects. For example, this loop : for (int i = 0; i < 10000; i++); This loop is "really" empty : no matter if you execute it or not, it doesn't give or take anything from the rest of the program (if not a delay).

Can you have an empty while loop in Java?

The body of the while can be empty. This is because a null statement, one that consists only of a semicolon, is syntactically valid in Java.

Can we use empty for loop?

Empty Statement in a for Loop Here, the initialization block of the for loop contains nothing, hence an empty statement. For creating a loop that runs infinitely, we can use empty statements. However, if we use break statements inside the body of the loop, then the loop can terminate.

What is an empty for loop give an example in Java?

An empty loop is a loop which does not have any updation or value of iteration. For example, for(int i = 1;;) (in Java) An empty loop is infinite. kvargli6h and 42 more users found this answer helpful.


3 Answers

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?

like image 165
Gaurav Avatar answered Oct 28 '22 05:10

Gaurav


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.

like image 43
Joe Avatar answered Oct 28 '22 05:10

Joe


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.

like image 28
holgac Avatar answered Oct 28 '22 07:10

holgac