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

后端 未结 13 1717
无人共我
无人共我 2021-02-05 15:26

say suppose I have class as :

public class Age {

    private int age;

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

}

In my Main c

相关标签:
13条回答
  • 2021-02-05 15:39

    You won't see much change in performance unless if you are doing many operations inside the getAge() method.

    0 讨论(0)
  • 2021-02-05 15:40

    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.

    0 讨论(0)
  • 2021-02-05 15:41

    i think you will see no difference at runtime - assuming you do not create more than one Age class.

    0 讨论(0)
  • 2021-02-05 15:44

    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.

    0 讨论(0)
  • 2021-02-05 15:49

    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.

    0 讨论(0)
  • 2021-02-05 15:49

    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.

    0 讨论(0)
提交回复
热议问题