Java运算符性能算法与按位运算 [英] Java operators performance arithmetic vs bitwise

查看:129
本文介绍了Java运算符性能算法与按位运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在性能确实很重要的重复算术运算中,按位运算符会对性能产生正面还是负面影响?我尝试使用Google进行搜索,但无法获得确切的答案.

In repetitive arithmetic operations where performance really matters, do bitwise operators have a positive or negative impact on performance? I tried to Google it but couldn't get a definitive answer.

例如,我应该使用这个:

For example should i use this:

int s = 15 << 4;

或者这个:

int s = 15 * 16;

以提高我的应用程序的性能.

to improve the performance of my application.

运算符优先级是否与性能相关?

推荐答案

即使这些操作不是

Even if these operations are not compile-time constant expressions (for example n << 4), the virtual machine would select the faster implementation during the JIT compilation, so you can write in either way which is most readable for you. The performance will be the same.

这是 HotSpot JVM C2 JIT编译器的C ++代码,它用左移将乘法替换为2的幂.在下面的内容中,您可能会发现一些常量的更多优化方法(例如,将n * 12替换为(n << 3) + (n << 2)).

Here's the C++ code of HotSpot JVM C2 JIT compiler which replaces multiplication to power-of-two with the left shift. A little below you may find more optimizations for some constants (like replacing n * 12 with (n << 3) + (n << 2)).

这篇关于Java运算符性能算法与按位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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