Re: Do any Java compilers or JVMs optimize getter method calls?
david.karr wrote:
I prefer to reference instance variables through getters, as opposed
to direct access to them. However, there's "obviously" going to be a
small time penalty for that. I did some timings in Eclipse, and I
found direct reads were a tiny fraction faster than through the getter
call (no surprise), and the difference between the setter and a direct
write was even smaller (I tested 100000000 iterations, adding up the
nanosecond intervals of each type of access).
I'm wondering whether there are any compiler/JVM combinations that
optimize getter calls to be the same as a direct access? I can see
from the bytecode in Eclipse that there is no optimization at that
level, but I don't know if the JVM will do any optimization in some
cases. It didn't appear to do it in Eclipse, but I don't know if other
JVMs would act differently.
You cannot tell optimization from the bytecode, because optimization happens
in the JVM.
Doesn't Eclipse use the JVM installed on your system? What JVM is installed
on your system?
What options are you passing to the JVM now?
The most significant optimizations occur with the "-server" option to the
"java" command (or equivalent). Others are possible. They are documented on
java.sun.com and elsewhere.
Methods declared as 'final' tend to be inlined and run faster than methods not
so qualified.
When running your benchmarks, let the loop run a bunch of times before you
start timing. That lets the Hotspot compiler analyze the run and figure out
what to optimize.
The tricky thing with Hotspot is that it might inline or enregister or loop
unroll or compile certain things at some times, then de-optimize them at other
times depending on the moment-by-moment profile of the execution.
The compiler (i.e., "javac") tends to have negligible impact on optimization,
since optimization happens at run time.
--
Lew