If I have two constants known at compile time, the Java compiler will fold them.
final static int foo = 2;
final static int bar = 17;
int myVariable;
int myFunction(){
return foo*bar + myVariable;
}
At runtime, myFunction will return 34 + myVariable, and won't need to calculate 2*17 as that was done at compile time.
My question is: would it do the same if the constants aren't known until runtime? I believe this is called runtime code specialization.
final int foo;
final int bar;
int myVariable;
int myFunction(){
return foo*bar + myVariable;
}
If foo and bar were initialised as 2 and 17 in the object's constructor, would myFunction be specialised to return 34 + myVariable, or would it still calculate foo*bar every time the function was called, even though foo*bar would never change?
*Edit: I'm referring to the newest version of the JVM, 1.7.0_45.
Hotspot Compiled Assembler
Java Code
Java Version
Conclusions
No, it can't.
While I do not understand most of what is going on there, it appears that the function has been inlined into the loop at
[Verified Entry Point]
, but that the constants are not folded because there is a multiplication is still occurring atimul eax,DWORD PTR [rsi+0xc]
.