Is assigning a frequently used field to a local variable more efficient?

前端 未结 1 1877
别那么骄傲
别那么骄傲 2021-01-22 16:54

I was reading the source of java.util.HashMap and noticed it almost always assign the table field to a local variable if the value is used more than on

1条回答
  •  抹茶落季
    2021-01-22 17:42

    By putting a member field into the local scope (that is, the current stackframe), you fix the reference for the entire execution of the method. So you have the same reference to the same object for every use.

    Without putting it into the local scope, every access to the field is via this reference (implicitly or explicitly). So for every access, the JVM has to get the current value of the field - which theoretically may have change since the last access.

    On top of being more reliable, the JIT may optimize the access, i.e. in loops (inlining values, whatever).

    Impacts on performance are rather small, but measurable.

    0 讨论(0)
提交回复
热议问题