Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do java caches results of the methods

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?

like image 880
VB_ Avatar asked Jun 15 '14 20:06

VB_


2 Answers

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).

like image 92
apangin Avatar answered Sep 21 '22 13:09

apangin


No.

Simply put, Java does not cache method results, since methods can return different values every time.

like image 33
Anubian Noob Avatar answered Sep 22 '22 13:09

Anubian Noob