java true,Java性能:真实与Boolean.TRUE

Which is better in terms of performance and efficient memory usage?

Boolean isItTrue(arg){

return Boolean.TRUE;

}

boolean isItTrue(arg){

return Boolean.TRUE

}

Boolean isItTrue(arg){

return true;

}

boolean isItTrue(arg){

return true;

}

It should be faster and easier to work with primitive types, but in other hand when using reference to static object, no new value created. Or may be it is optimized on compiler level and all true and false are replaced by references to the static objects to save memory?

解决方案

Firstly, the performance advantage of using any one over the others is most likely to be too small to be relevant. Code simplicity / readability / maintainability is a far more important ... in the vast majority of cases.

None of the examples involve creating an Boolean instances. It is theoretically possible that 3 of the 4 will trigger initialization of the Boolean class ... and that your application wouldn't otherwise have done that. In that highly unlikely event, your entire application will allocate 2 objects that wouldn't otherwise have been allocated.

This one will be equal to or faster than all of the others because it simply entails setting a register to zero.

boolean isItTrue(arg){

return true;

}

Taken in isolation, this has to load a static reference from memory, rather than zero a register. However, the JIT compiler may be able to optimize this away in some circumstances.

Boolean isItTrue(arg){

return Boolean.TRUE;

}

On the face of it, this involve a call to Boolean.valueOf(true) to "box" the true, but the JIT compiler should be able to optimize it to the same code as the previous one by inlining the call.

Boolean isItTrue(arg){

return true;

}

On the face of it, this involves a call to Boolean.booleanValue(Boolean.TRUE) to "unbox" the Boolean. This call can be inlined. It is also possible that the JIT compiler can avoid loading the reference to the Boolean object and fetching its value field.

boolean isItTrue(arg){

return Boolean.TRUE

}

Bottom line is that it the relative performance of the 4 alternatives depends on how successful the JIT compiler will be in optimizing. That will depend on the context, the specific of the JIT compiler, the JVM settings, and so on. In the best case, the JIT compiler could (at least in theory) produce the same (optimal) code for all of them.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值