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.
You won't see much change in performance unless if you are doing many operations inside the getAge() method.
The tricky part is understanding that modern JVM's do aggressive optimizations when compiling byte code based on the knowledge available at runtime.
If, for instance, a given method is not overridden in a subclass it can be treated exactly the same as a final method, allowing the JVM to inline a copy of its code in the calling method instead of explicitly doing a method call. (If conditions change, those classes are then simply considered new and hence recompiled later based on the new conditions).
This means that get/set for bean attibutes (where the values are simply stored and retreived, and not calculated) are very cheap and you should do the calls everytime and expect the JVM to detect the possible optimizations and apply them.
In this case, I'd suggest don't look at performance, look at usability and code reuse. Your current implementation is the simplest of getters, one that returns an integer.
But what if somewhere down the line you store a person's birthdate and want to dynamically generate the age? If you simply call the property directly, you then are forced to refactor your code. However, altering getAge()'s internals, you can put the calculation in there, and you're done.
I'd really like programming languages to introduce a 'super-private' property / field modifier, one that basically says 'You can only access this property through its accessor'.
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.