I use JMH to specify the complexity of the operation. If you've never worked with JMH, don't worry. JMH will just launch the estimateOperation
method multiple times and then get the average time.
Question: [narrow] will this program calculate Math.cbrt(Integer.MAX_VALUE)
each time? Or it just calculate it once and return cached result afterwards?
@GenerateMicroBenchmark
public void estimateOperation() {
calculate();
}
public int calculate() {
return Math.cbrt(Integer.MAX_VALUE);
}
Question: [broad]: Does JVM ever cache the result of the methods?
The method return value is never cached. However, unnecessary calls may be eliminated by JIT compiler in run-time due to certain optimizations like constant folding, constant propagation, dead code elimination, loop invariant hoisting, method inlining etc.
For example, if you replace Math.cbrt
with Math.sqrt
or with Math.pow
, the method will not be called at all after JIT compilation, because the call will be replaced by a constant. (The optimization does not work for cbrt
, because it is a rare method and it falls to a native call which is not intrinsified by JVM).
No.
Simply put, Java does not cache method results, since methods can return different values every time.
Yes it will invoke that code everytime it is being called
public int calculate() {
return Math.cbrt(Integer.MAX_VALUE);
}
public double calculate();
Code:
0: ldc2_w #3 // double 2.147483647E9d
3: invokestatic #5 // Method java/lang/Math.cbrt:(D)D
6: dreturn
to have cache, simply replace that magic number by
private static final field
private static final double NUMBER = Math.cbrt(Integer.MAX_VALUE);
Answer to narrow question: It depends on the JVM implementation and how the code is interpreted.
Answer to broad question: No since, as Anubian also pointed out, methods can return different values on each call.
来源:https://stackoverflow.com/questions/24233716/do-java-caches-results-of-the-methods