Is there any differences between doing
Field field = something.getSomethingElse().getField();
if (field == 0) {
//do something
}
somelist.add(field);
This post talks about the CLI VM instead of the JVM, but each is able to do similar things, so I believe it's relevant.
I'm handling this particular problem in a special way for my JIT. Note that the description here is conceptual and the code implements it in a slightly different way for performance reasons. When I load an assembly, I make a note in the method descriptor if it simply returns a member field. When I JIT other methods later, I replace all call
instructions to these methods in the byte code with a ldfld
instruction before passing it to the native code generator. In this way, I can:
ldfld
takes less processor time to JIT than call
).I have no doubt that the big names in VM technologies are already implementing something similar to (and probably better than) this in their products.
There is a difference in that accessing variables through getters results in a method call. The JVM might conceivably be able to optimize the method call away under some circumstances, but it is a method call.
That said, if the biggest bottleneck or performance problem in your code is overhead from accessor methods, I would say that you don't have a lot to worry about.
It's a negligible detriment. Don't concern yourself with it too much or you'll fall prey to premature optimization. If your application is slow, this isn't the reason why.