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?

ealeon
  • 12,074
  • 24
  • 92
  • 173
  • 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. – BeUndead Feb 07 '19 at 16:58
  • @user2478398 no computation. it's just a parameter of a constructor stored via \@Getters annotation – ealeon Feb 07 '19 at 17:00
  • 1
    always its a better way even its easier during refactor `int objValue = myObj.getValue()` – Ashok Kumar N Feb 07 '19 at 17:01
  • Avoid premature optimization and strive to [write dumb code](https://www.oracle.com/technetwork/articles/java/devinsight-1-139780.html) – Hovercraft Full Of Eels Feb 07 '19 at 17:01
  • 1
    Other thing to consider whether that value which is returned by `myObj.getValue()` could be changed by other threads. – Ivan Feb 07 '19 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. – vavasthi Feb 07 '19 at 17:01
  • As long as you are not planning on changing the value, I would call it once and store. Not for any potential optimizations, just because it's a bit easier to read that way. – Stalemate Of Tuning Feb 07 '19 at 17:01

1 Answers1

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.