2

I have a method where it takes in an object as an input

void doSomething(MyObject myObj) {
   ///
}

In this method, it calls myObj.getValue() several times for various reasons

Is it better to just store as int objValue = myObj.getValue() and use objValue throughout the method, instead keep calling myObj.getValue()

why? why not?

7
  • 2
    It entirely depends on what getValue does. If it accesses a final field or other clearly fixed property the JIT compiler will optimise that away most of the time. If it actually runs some computation then it will rerun the computation each time. Commented Feb 7, 2019 at 16:58
  • @user2478398 no computation. it's just a parameter of a constructor stored via \@Getters annotation Commented Feb 7, 2019 at 17:00
  • 1
    always its a better way even its easier during refactor int objValue = myObj.getValue() Commented Feb 7, 2019 at 17:01
  • 1
    Other thing to consider whether that value which is returned by myObj.getValue() could be changed by other threads. Commented Feb 7, 2019 at 17:01
  • 1
    If you can afford to declare the field as final, then no need to store it into a temporary. The compiler can optimize it. If it is not final then storing it into a temporary may give you some efficiency. Commented Feb 7, 2019 at 17:01

1 Answer 1

3

If getValue() is a timeconsuming operation it will most likely be better to call it once only and store the value in a variable.

If you call it several times, you might not in practice get any performance improvements, depending on compiler optimizations.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.