Java:在双重检查惯用语中使用局部变量 [英] Java: using a local variable in double check idiom
问题描述
Josh Bloch提到在双重检查惯用语中使用局部变量以提高性能(EJ,第二版,第284页),并说示例代码在其机器上的运行速度比没有局部变量的计算机快25%.所以问题是,为什么速度更快?对于局部变量版本,它将访问实例变量3次,在正常情况下,它将访问实例变量4次.是"25%"增长背后的原因还是其他原因?
Josh Bloch mentions using a local variable in double check idiom for possible performance improvement (EJ, 2nd ed. p284) and says the example code runs about 25% faster on his machine compared to that without a local variable. So the question is, why is it faster? In case of local variable version, it accesses the instance variable 3 times and in normal case it accesses the instance variable 4 times. Is this the reason behind '25%' increase or are there any other reasons?
只有在首次创建实例时,才进行3或4次访问.此后是1或2次.
3 or 4 times access is only when the instance is first created. Thereafter, it's 1 or 2 times.
检查该问题的可接受答案以查看示例代码.我认为这是针对Java 6的.如何解决双重检查锁定被破坏"的问题,请参见解决方案".用Java声明吗?
check the accepted answer for this question to see the example code. I think this is for Java 6. How to solve the "Double-Checked Locking is Broken" Declaration in Java?
推荐答案
最基本的是,访问 volatile
变量要比访问本地变量慢.声明局部变量时,基本上是在方法中缓存易失变量的值.
The basic thing is that accessing the volatile
variable is slower, than accessing the local one. When you declare a local variable, you are basically caching the value of a volatile variable inside the method.
在正常情况下(没有局部变量),您将访问volatile变量:
In the normal (without a local variable) case you are accessing the volatile variable:
- 在
synchronized
子句之前的第一个if
中 - 在
synchronized
子句中的第二个if
中 - 在第二个
if
中,为它分配值 - 在
return
语句中
- In the first
if
before thesynchronized
clause - In the second
if
inside thesynchronized
clause - Inside the second
if
where you assign a value to it - In the
return
statement
现在,如果您引入局部变量,则只需访问 volatile
变量三次:
Now, if you introduce a local variable, you only access the volatile
variable three times:
- 在为
synchronized
子句之前的第一个if
分配局部变量时 - 在
synchronized
子句中为第二个if
分配局部变量时 - 在第二个
if
中,为它分配值
- When assigning the local variable for the first
if
before thesynchronized
clause - When assigning the local variable for the second
if
inside thesynchronized
clause - Inside the second
if
where you assign a value to it
通过返回局部变量,您不会在 return
语句中访问它,从而提高了速度.
You do not access it in the return
statement, by returning the local variable, thus giving you a speed boost.
这篇关于Java:在双重检查惯用语中使用局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!