JIT not optimizing loop that involves Integer.MAX_VALUE
Solution 1:
I have not dug up the Java Language Specification, but I'd guess that it has to do with this difference:
i++ < (Integer.MAX_VALUE - 1)
never overflows. Oncei
reachesInteger.MAX_VALUE - 1
it is incremented toInteger.MAX_VALUE
and then the loop terminates.i++ < Integer.MAX_VALUE
contains an integer overflow. Oncei
reachesInteger.MAX_VALUE
, it is incremented by one causing an overflow and then the loop terminates.
I assume that the JIT compiler is "reluctant" to optimize-out loops with such corner conditions - there was a whole bunch of bugs w.r.t. loop optimization in integer overflow conditions, so that reluctance is probably quite warranted.
There may also be some hard requirement that does not allow integer overflows to be optimized-out, although I somehow doubt that since integer overflows are not directly detectable or otherwise handled in Java.