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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With