Calling a getter multiple times or calling once and assigning to a variable?

GuruKulki picture GuruKulki · May 12, 2010 · Viewed 8.1k times · Source

say suppose I have class as :

public class Age {

    private int age;

    public int getAge() {
       return this.age;
    }

}

In my Main class I am calling the getAge() method many times.

So I wanted to know is it advisable to call so many times or call once and assign it to some variable and use that variable.

Which is best and why?

Answer

unholysampler picture unholysampler · May 12, 2010

This is likely a situation where you are optimizing before you know you need to. The value is just an integer so it is not taking up a lot of memory if you store the value in multiple places. At the same time, it is a very simple method call that will not take much time to execute. Write it in a way that you feel is most readable. Then after you have a solid version of the code, you can use a profiling tool to see if there is a noticeable difference.