Which function is faster (p is atomic public int property of MyObject):
public static boolean check(MyObject o1, List<MyObject> list) {
int p = o1.p;
for (int i = 0; i < 1000000; i++) {
MyObject o = list.get(i);
if (o.p < p) return false;
}
return true;
}
or
public static boolean check(MyObject o1, List<MyObject> list) {
for (int i = 0; i < 1000000; i++) {
MyObject o = list.get(i);
if (o.p < o1.p) return false;
}
return true;
}
So by using the local variable p we cache the object property call or it is done inline by the compiler optimization?
Short Answer: It depends
Slightly longer Answer: It depends on the compiler, the VM and the settings of your VM.
Background: Using the HotSpot VM (most common flavor) in server mode will make both variants equal since the VM does loop invariant hoisting in server mode. In client mode this may be done, may not be done or even may be done later if the VM considers it worthy of optimisations.
Loop invariant hoisting is one of the loop optimisation, that is implemented into most modern compilers (or in the case of Java, VMs). As for the code generated by javac: Without further optimization done by the VM your first code sniplet will perfom faster.
—
As you can see, the getfield operation from line 20 in the second example lies in line 1 in the first and is outside of the loop (lines 7 to 39 in variant 1 and lines 2 to 35 in variant 2) and is therefore only executed ondced instead of 1000000 times.