Based on the discussions around an answer to this question, I discovered a really strange behaviour of the Java Hotspot optimizer. The observed behaviour can at least be seen in the Oracle VM 1.7.0_17, but seem to occur in older Java 6 versions as well.
First of all, I was already aware of the optimizer obviously being aware that some methods in the standard API are invariant and have no side effects. When executing a loop like double x=0.5; for(double d = 0; d < Math.sin(x); d += 0.001);
, the expression Math.sin(x)
is not evaluated for each iteration, but the optimizer is aware that the method Math.sin
has no relevant side effects and that the result is invariant, as long as x
is not modified in the loop.
Now I noticed, that simply changing x
from 0.5 to 1.0 disabled this optimization. Further tests indicate that the optimization is only enabled if abs(x) < asin(1/sqrt(2)). Is there a good reason for that, which I don't see, or is that an unnecessary limitation to the optimizing conditions?
Edit: The optimization seem to be implemented in hotspot/src/share/vm/opto/subnode.cpp
Math.sin
is an intrinsic method in Java 1.7 (possibly before) so the code run is not the Java code shown in the JDK source... – Olia