Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 998
GuruKulki Avatar asked May 12 '10 17:05

GuruKulki


5 Answers

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.

like image 66
unholysampler Avatar answered Nov 05 '22 10:11

unholysampler


Don't try to micro-optimize this, unless you find that it's truly a bottleneck while profiling. I'd use the getAge() accessor method, since it's most likely the most maintainable and obvious solution.

That being said, the two approaches are likely to perform exactly the same. At runtime, the JIT will most likely optimize away the getAge() call entirely, so it will be a single primitive access in both cases.

like image 24
Reed Copsey Avatar answered Nov 05 '22 11:11

Reed Copsey


There may be some performance overhead of calling the getAge() method many many times, but I suggest you consider The Sad Tragedy of Micro-Optimization Theater.

like image 3
Cesar Avatar answered Nov 05 '22 12:11

Cesar


This is something that you, as the API writer, have to indicate to the caller.

In general, if you are simply returning a property, you can mark the call as a final (if you are not offering an actual interface). That should reduce the costs of calls since the compiler would be more likely to inline the function.

If the cost of calculating the property is expensive (E.g., a string lookup), document it in the JAvaDocs for that method, and indicate to the caller that they may want to obtain the value once and cache it.

like image 3
Uri Avatar answered Nov 05 '22 11:11

Uri


Don't bother. It's absolutely not worth micro-optimizing like this. Wait until you finish your code, then it runs too slowly, then get out a profiler and work on what the profiler tells you is the source of the problem.

Premature optimization is the root of all evil.

like image 2
Puppy Avatar answered Nov 05 '22 10:11

Puppy