In Java is there a performance difference between referencing a field through getter versus through a variable?

后端 未结 9 1100
失恋的感觉
失恋的感觉 2020-12-20 17:49

Is there any differences between doing

Field field = something.getSomethingElse().getField();
if (field == 0) {
//do something    
}
somelist.add(field);


        
相关标签:
9条回答
  • 2020-12-20 18:33

    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:

    1. Save time in the JIT (ldfld takes less processor time to JIT than call).
    2. Inline properties even in the baseline compiler.
    3. By and large guarantee that using the public properties/private fields pattern will not incur a performance penalty of any kind when the debugger is detached. (When a debugger is attached I can't inline the accessors.)

    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.

    0 讨论(0)
  • 2020-12-20 18:41

    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.

    0 讨论(0)
  • 2020-12-20 18:48

    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.

    0 讨论(0)
提交回复
热议问题