【Java源码解读——释疑】为什么将类成员变量复制为方法本地变量

.

参考:

JDK源码中经常会出现一种代码模式:将类成员变量复制到方法本地变量上。

如:String.compareTo() 方法中会将类成员变量 value 复制为方法本地变量 v1:

Java代码

 

  1. public int compareTo(String anotherString) {  

  2.   byte v1[] = value;  

    扫描二维码关注公众号,回复: 8587562 查看本文章
  3.   byte v2[] = anotherString.value;  

  4.   ...  

  5. }  

我们可从官方邮件列表得知原因:《Performance of locally copied members ?

It's a coding style made popular by Doug Lea.

It's an extreme optimization that probably isn't necessary;

you can expect the JIT to make the same optimizations.

(you can try to check the machine code yourself!)

Nevertheless, copying to locals produces the smallest bytecode, and for low-level code it's nice to write code that's a little closer to the machine.

Also, optimizations of finals (can cache even across volatile reads) could be better. John Rose is working on that.

For some algorithms in j.u.c, copying to a local is necessary for correctness.

即:

这是一种极端的优化方式,而且可能没啥用。你可以期望 JIT 也会执行相同的优化。

将类成员变量复制为方法本地变量可使得生成的字节码更小;也更容易编写靠近机器的底层代码。

在某些算法中(特别是JDK并发包中的算法),复制为本地变量,或使用final变量,对于保证并发正确性很有必要。

所以我们并不需要对这种代码模式过于担心。你做好并发/同步相关正确性编码,保证算法正确性就行,不需要去刻意模仿使用这种代码模式。

(无论是否使用这种代码模式,算法正确性都是需要保证的嘛!)

发布了219 篇原创文章 · 获赞 3 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/hchaoh/article/details/103904964