say suppose I have class as :
public class Age {
private int age;
public int getAge() {
return this.age;
}
}
In my Main c
You won't see much change in performance unless if you are doing many operations inside the getAge() method.
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.
i think you will see no difference at runtime - assuming you do not create more than one Age class.
Depending on how your application is designed, the two options might actually give different results! If the age instance you're using is shared and mutable, different places in your application might change its value in between your calls to getAge()
. In this case, it's a matter of correctness to decide which is the best option for your code, and it's up to you to decide. As the old adage says: "first make it right, then make it fast". And, as others have already mentioned, you probably won't need to worry about the "make it fast" part in this case.
A related example is when you're changing a collection while iterating through it. You have to iterate over a snapshot to not get a ConcurrentModificationException
.
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.