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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With