Do java caches results of the methods

别等时光非礼了梦想. 提交于 2019-12-07 04:56:59

问题


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?


回答1:


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




回答2:


No.

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




回答3:


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



回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!