In Java is there a performance difference between referencing a field through getter versus through a variable?

getter, java, performance, reference, variables

Solution

Assuming that `getSomethingElse()` is defined as

public SomethingElse getSomethingElse() {
    return this.somethingElse;
}

performance difference will be minimal (or zero if it'll get inlined). However, in real life you can not always be sure that's the case - there may be some processing happening behind the scenes (not necessarily in the object itself but, say, via AOP proxy). So saving the result in the variable for repeat access may be a good idea.

Problem

Is there any differences between doing ``` Field field = something.getSomethingElse().getField(); if (field == 0) { //do something } somelist.add(field); ``` versus ``` if (something.getSomethingElse().getField() == 0) { //do something } somelist.add(something.getSomethingElse().getField()); ``` Do references to the field through getters incur a performance penalty or is it the same as referencing an assigned variable? I understand that the variable is just a reference to the memory space, so the getter should just be another way to get at that memory space. Note that this is an academic question (school of just curious) rather then a practical one.

Original source