I\'ve been looking at at some of the java primitive collections (trove, fastutil, hppc) and I\'ve noticed a pattern that class variables are sometimes declared as fina
The final
keyword is a red herring here.
The performance difference comes because they are saying two different things.
public void forEach(IntIntProcedure p) {
final boolean[] used = this.used;
for (int i = 0; i < used.length; i++) {
...
}
}
is saying, "fetch a boolean array, and for each element of that array do something."
Without final boolean[] used
, the function is saying "while the index is less than the length of the current value of the used
field of the current object, fetch the current value of the used
field of the current object and do something with the element at index i
."
The JIT might have a much easier time proving loop bound invariants to eliminate excess bound checks and so on because it can much more easily determine what would cause the value of used
to change. Even ignoring multiple threads, if p.apply
could change the value of used
then the JIT can't eliminate bounds checks or do other useful optimizations.