CodeBlue
CodeBlue

Reputation: 15409

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?

In effect, the compiler or JVM assumes there are no side effects of the statement and therefore removes it for optimization.

Upvotes: 0

Views: 173

Answers (1)

maaartinus
maaartinus

Reputation: 46492

As stated in the comments, it's not exactly a no-op: At the very least, it must perform a null check. Moreover, there may be subclasses of ArrayList working differently. 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.

The compiler (JIT, not javac) must be able to prove that it's really a side-effect free. Usually, it's quite simple as

  • it knows, if there are any overriden implementation of ArrayList.size().1
  • If there are none, then it sees that it's a simple getter and inlines it.23
  • 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 (e.g., due to a previous useless statement :D).
  • Otherwise, it can get moved out of the loop, if arrayList is a loop invariant.

Will any Java compiler or JVM ignore this statement for optimization purposes?

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.
2 Assuming it decides it's worth optimizing.
3 This may fail, if the method is already over inlining limit, e.g., due to bad coding style or because of other inlining.

Upvotes: 4

Related Questions