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

后端 未结 13 1686
无人共我
无人共我 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:55

    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.

提交回复
热议问题