Reputation: 2061
I have question about JIT optimization. I compiled a simple piece of code:
class btest
{
static final boolean flag=false;
public final void foo(int x)
{
if(flag) {a=x; b=x*2; c=x*3;}
}
public void bar(int y) {foo(y);}
int a,b,c;
};
flag
is set to false
so foo()
is perfectly compiled to empty code - just returns.
But bar()
still calls it.
Is it possible that JIT will eliminate this call?
Does it matter if flag
belongs to external class?
regards
Upvotes: 0
Views: 128
Reputation: 718718
The JIT compiler would most likely be able to eliminate this.
But actually, I think that the if
statement is likely to be optimized away before then. The reason is in JLS 14.21 starting at the point where is says this:
"However, in order to allow the if statement to be used conveniently for "conditional compilation" purposes, the actual rules differ."
If goes on to say that that the compiler (that is the bytecode compiler!) may generate different code in your example depending on the known value of the condition at compile time.
Note that this special treatment only applies to if
statements, and only if the condition is a constant expression. (That term has a very specific meaning - see JLS 15.28) If you tried the same "trick" with a while
loop for example, you would get a compilation error complaining about unreachable code.
(This "conditional compilation" special treatment goes back to the early days of Java, and is part of the rationale for Gosling et al's decision to not include a preprocessor in the Java language.)
Upvotes: 1
Reputation: 533472
It can eliminate it and inline it in code.
Note: It can also do this for non-volatile non-final variables where it thinks the thread doesn't change the value. A common mistake is something like
boolean running = true;
public void run() {
while(running) {
// do something
}
}
public void stop() {
running = false;
}
A common misconception is that the thread might keep running for an while but stop at some unknown point, when actually the JIT might inline running
and never stop.
Upvotes: 4