简体   繁体   English

Java是否会优化最大操作?

[英]Will Java optimize max operations?

Given the following Java code, will the JRE optimizer replace the call to max with a call to Math.max ? 给定以下Java代码,JRE优化器是否将对max的调用替换为对Math.max的调用?

Unoptimized code 未优化的代码

public static void main(String[] args) {
  int max = max(3, 5);
}

public int max(int x, int y) {
  if (x < y) {
    return y;
  }
  else {
    return x;
  }
}

Optimized code 优化代码

public static void main(String[] args) {
  int max = Math.max(3,5)
}

No. How would the compiler know they are the same? 不会。编译器如何知道它们相同?

What makes you think Math.max would be faster anyway? 是什么让您认为Math.max会更快呢? There is no reason it would perform faster than your function. 它没有理由比您的功能执行得更快。

The compiler may well inline a simple function like that though - but that is down to the compiler. 编译器很可能内联这样的简单函数-但这取决于编译器。

Imagine how many libraries there are in a standard program. 想象一个标准程序中有多少个库。 How much effort would the compiler need to go to to scan all those libraries for identical code fragments. 编译器需要付出多少努力才能扫描所有这些库以查找相同的代码片段。 Then see how tiny the gains from identifying them would be. 然后看看识别它们会带来多大的收益。

Now also consider the case of multiple libraries where both define this method. 现在还要考虑多个库都定义了该方法的情况。 The compiler needs to leave both because otherwise one library becomes dependant on the other and what would happen if in the future one library changed or removed its definition of the method. 编译器需要同时离开这两个位置,因为否则一个库将依赖于另一个库,并且如果将来某个库更改或删除其方法定义会发生什么。

It's a huge messy can of worms for no real benefit in the end. 最终,这真是一大堆杂乱无章的蠕虫,无济于事。

There's a very good reason for Math.max to be faster than a handwritten method: It's on the list of intrinsic methods. 有一个很好的理由使Math.max比手写方法要快:它在固有方法列表中。 As it's a very simple operation, there might be no gain on a given CPU, but using it is probably a good idea. 因为这是一个非常简单的操作,所以给定的CPU可能没有任何收益,但是使用它可能是一个好主意。

For more complex operations there is a huge speed up from using intrinsics. 对于更复杂的操作,使用内在函数可以大大提高速度。 For example, the Java code of Long.numberOfLeadingZeros(long) is pretty long and make take a dozen cycles (or more with some branch mispredictions). 例如, Long.numberOfLeadingZeros(long)的Java代码很长,并且要花费十几个周期(或者由于分支错误预测而需要更多时间)。 As the Hotspot JVM knows this method and there's a corresponding i86 instruction, you can get it in a single cycle (even leaving room for other instructions to be executed concurrently). 由于Hotspot JVM知道此方法,并且有相应的i86指令,因此您可以在一个周期内获得它(甚至为同时执行其他指令留出空间)。

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

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