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)
).