0

Is calling a getter function in class that does not computation better than assign value to a new variable?

Example:

Class Test{
        private AnotherClass a;
        public AnotherClass getA(){
            return a;
        }
}

Is it better to keep calling getA() in a same function or todo AnotherClass var1 = getA(); then keep using var1 in that function.

I want to understand memory vs performance & how can we balance it.

Edit: Usage example: Consider another class being list

    AnotherClass var1 = test.getA();
    if(var1!=null){
    for(List var : var1){
// do something
}

or 

if(test.getA()!=null){
for(List var : test.getA())
// do something
}

Note this kind of behaviour can be done multiple time in multiple places.

StackFlowed
  • 6,664
  • 1
  • 29
  • 45
  • 1
    An object reference isn't very expensive for memory or computation. You should strive for readable code that makes sense, not nanosecond optimizations. – nanofarad Aug 21 '14 at 18:28
  • 1
    *calling getA() in a same function* will result into `StackOverflowError` – Braj Aug 21 '14 at 18:28

1 Answers1

2

See this question: Java Method invocation vs using a variable.

In general, you should code for readability rather than performance. The compiler may very well optimize away get() calls for you. If it doesn't, and this turns out to be an issue, you can always profile your code after it is finished to identify and eliminate bottlenecks. To start off, though, definitely go for readability.

Community
  • 1
  • 1
Alex Kleiman
  • 709
  • 5
  • 14