Reputation: 15409
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
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
ArrayList.size()
.1arrayList
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