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

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

    I'll try to say with code examples what the other answer already said.

    In the case you presented the call for getAge() is very very simple, and the cost of calling it is almost nothing. Don't bother with it in this case.

    But if your getAge was something fancy that do lots of calculations or access IO resources, like:

    public int getAge() {
       return slowService.calculateAgeByBirthDate(birthDate); // it takes 2 seconds to execute for every call
    }
    

    Then for sure it would be a good idea to cache de result and use it. Because if you call it 30 times your code will take 1 minute to complete.

提交回复
热议问题