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

后端 未结 13 1687
无人共我
无人共我 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题