简体   繁体   English

是否有任何Java编译器或JVM忽略优化语句?

[英]Does any Java compiler or JVM ignore a statement for optimization?

Suppose we have the following statement 假设我们有以下语句

arrayList.size(); 

This statement in itself does nothing. 该语句本身不执行任何操作。 Will any Java compiler or JVM ignore this statement for optimization purposes? 为了优化目的,任何Java编译器或JVM都会忽略此语句吗?

In effect, the compiler or JVM assumes there are no side effects of the statement and therefore removes it for optimization. 实际上,编译器或JVM假定该语句没有副作用,因此将其删除以进行优化。

As stated in the comments, it's not exactly a no-op: At the very least, it must perform a null check. 如评论中所述,这并非完全禁止操作:至少,它必须执行null检查。 Moreover, there may be subclasses of ArrayList working differently. 此外,可能存在ArrayList子类以不同的方式工作。 In theory, they could even fetch the data from a database or alike. 从理论上讲,他们甚至可以从数据库等获取数据。 Normally, nobody would subclass an ArrayList for doing this, but such a List implementation makes some sense. 通常,没有人会这样做来ArrayList ,但是这样的List实现是有道理的。

The compiler (JIT, not javac) must be able to prove that it's really a side-effect free. 编译器(JIT,不是Javac)必须能够证明它确实没有副作用。 Usually, it's quite simple as 通常,它很简单

  • it knows, if there are any overriden implementation of ArrayList.size() . 它知道是否存在ArrayList.size()任何重写的实现。 1 1个
  • If there are none, then it sees that it's a simple getter and inlines it. 如果没有,则看到它是一个简单的getter并将其内联。 2 3 2 3
  • This reduces to problem to a useless field load, which gets reduces to the null check. 这减少了对无用字段负载的问题,并将其减少为空检查。
  • The null check can get eliminated too, if it was performed earlier (eg, due to a previous useless statement :D). 如果空检查是更早执行的(例如,由于先前的无用语句:D所致),则空检查也可以被消除。
  • Otherwise, it can get moved out of the loop, if arrayList is a loop invariant. 否则,如果arrayList是循环不变的,则可以将其移出循环。

Will any Java compiler or JVM ignore this statement for optimization purposes? 为了优化目的,任何Java编译器或JVM都会忽略此语句吗?

So I'd conclude that it's quite probable to happen. 所以我得出结论,这很有可能发生。


1 This may change later as such a class gets loaded and then a deoptimization will take place. 1这可能会在以后加载此类时更改,然后进行取消优化
2 Assuming it decides it's worth optimizing. 2假设它值得优化。
3 This may fail, if the method is already over inlining limit, eg, due to bad coding style or because of other inlining. 3如果方法已经超出内联限制,则可能会失败,例如,由于不良的编码样式或其他内联。

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

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