2

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 once in the method.

Since this class is documented to be not thread-safe and the field is not volatile, what's the point of this? Does it make the code more efficient?

billc.cn
  • 7,187
  • 3
  • 39
  • 79
  • one common reason is to prevent frequent gc sweeps – Sarthak Mittal Oct 25 '16 at 09:59
  • This may explain it: http://stackoverflow.com/questions/6602922/is-it-faster-to-access-final-local-variables-than-class-variables-in-java – PeterMmm Oct 25 '16 at 10:02
  • If the read is expensive, it can make more efficient, but in general a local variable is useful if it makes the code clearer. – Peter Lawrey Oct 25 '16 at 10:17
  • The class not being thread-safe is in effect a good reason to use a local variable, so a second occurrence refers to the same object as the first. A javadoc warning is not a sufficient measure. Evidently they _tried_ to write good code as far as possible. – Joop Eggen Oct 25 '16 at 10:22

1 Answers1

5

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.

Gerald Mücke
  • 10,724
  • 2
  • 50
  • 67