简体   繁体   English

Java运算符性能算法与按位运算

[英]Java operators performance arithmetic vs bitwise

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. 我尝试使用Google进行搜索,但无法获得确切的答案。

For example should i use this: 例如我应该使用这个:

int s = 15 << 4;

or this: 或这个:

int s = 15 * 16;

to improve the performance of my application. 来提高我的应用程序的性能。

Also does operator precedence correlate with performance? 运算符优先级也与性能相关吗?

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. 即使这些操作不是编译时常量表达式 (例如n << 4 ),虚拟机也会在JIT编译过程中选择更快的实现,因此您可以用最容易理解的任何一种方式编写。 The performance will be the same. 性能将是相同的。

Here's the C++ code of HotSpot JVM C2 JIT compiler which replaces multiplication to power-of-two with the left shift. 这是HotSpot JVM C2 JIT编译器的C ++代码 ,用左移将乘法替换为2的幂。 A little below you may find more optimizations for some constants (like replacing n * 12 with (n << 3) + (n << 2) ). 在下面一些地方,您可能会发现一些常量的更多优化方法(例如,用(n << 3) + (n << 2)代替n * 12 )。

In this case you could use either. 在这种情况下,您可以使用其中任何一个。

Both are compile-time evaluable constant expressions so the compiler will perform the operation. 两者都是编译时可评估的常量表达式,因此编译器将执行该操作。 So the runtime will not be impacted at all. 因此,运行时完全不会受到影响。

If you had contrived an example that was only evaluable at runtime, then it would have been harder to say, but if I were you I'd trust the compiler in any case. 如果您设计了一个仅在运行时可评估的示例,那么很难说,但是如果您是我,无论如何我都相信编译器。 Always use the appropriate operator for your task so bugs don't creep in. You can always profile performance. 始终对任务使用适当的运算符,以防止错误蔓延。您始终可以分析性能。

This code 这段代码

public class A {
    public static void main(String[] args) {
        int a = 15 << 4;
        int b = 15 * 16;
    }
}

is compiled to 编译为

  public static void main(java.lang.String[]);
    Code:
       0: sipush        240
       3: istore_1
       4: sipush        240
       7: istore_2
       8: return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM