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

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

提交回复
热议问题