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?
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).
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.
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.
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.
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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With