将频繁使用的字段分配给局部变量是否更有效? [英] Is assigning a frequently used field to a local variable more efficient?

查看:61
本文介绍了将频繁使用的字段分配给局部变量是否更有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 java.util.HashMap 的="nofollow">源,并注意到,如果使用的值大于方法中一次.

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?

推荐答案

通过将成员字段放入本地范围(即当前堆栈框架)中,可以为方法的整个执行固定引用.因此,每次使用时,您对同一对象都有相同的引用.

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.

无需将其放入本地范围,对字段的每次访问都是通过 this 引用(隐式或显式)进行的.因此,对于每次访问,JVM都必须获取该字段的当前值-从理论上讲,自上一次访问以来,该值可能会发生变化.

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.

除了更可靠之外,JIT还可以优化访问,即循环(内联值,无论如何).

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.

这篇关于将频繁使用的字段分配给局部变量是否更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆