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

.

参考:

 

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

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

Java代码

 

  1. public int compareTo(String anotherString) {  

  2.   byte v1[] = value;  

  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变量,对于保证并发正确性很有必要。

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

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值