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

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

    The tricky part is understanding that modern JVM's do aggressive optimizations when compiling byte code based on the knowledge available at runtime.

    If, for instance, a given method is not overridden in a subclass it can be treated exactly the same as a final method, allowing the JVM to inline a copy of its code in the calling method instead of explicitly doing a method call. (If conditions change, those classes are then simply considered new and hence recompiled later based on the new conditions).

    This means that get/set for bean attibutes (where the values are simply stored and retreived, and not calculated) are very cheap and you should do the calls everytime and expect the JVM to detect the possible optimizations and apply them.

提交回复
热议问题