Premature optimization in Java: when to use “x = foo.getX()” vs simply “foo.getX()”

后端 未结 8 3159
醉话见心
醉话见心 2021-02-19 14:40

When I find myself calling the same getter method multiple times, should this be considered a problem? Is it better to [always] assign to a local variable and call only once?

8条回答
  •  轮回少年
    2021-02-19 15:15

    That depends on what getX() actually does. Consider this class:

    public class Foo {
        private X x;
    
        public X getX() { return x; }
    }
    

    In this case, when you make a call to foo.getX(), JVM will optimize it all the way down to foo.x (as in direct reference to foo's private field, basically a memory pointer). However, if the class looks like this:

    public class Foo {
        private X x;
    
        public X getX() { return cleanUpValue(x); }
    
        private X cleanUpValue(X x) {
            /* some modifications/sanitization to x such as null safety checks */
        }
    }
    

    the JVM can't actually inline it as efficiently anymore since by Foo's constructional contract, it has to sanitize x before handing it out.

    To summarize, if getX() doesn't really do anything beyond returning a field, then there's no difference after initial optimization runs to the bytecode in whether you call the method just once or multiple times.

提交回复
热议问题