Is it faster to access final local variables than class variables in Java?

前端 未结 5 1779
闹比i
闹比i 2020-12-06 01:07

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

5条回答
  •  粉色の甜心
    2020-12-06 01:57

    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.

提交回复
热议问题