Do java caches results of the methods

自古美人都是妖i 提交于 2019-12-05 10:41:40

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.

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