java缓存方法的结果 [英] Do java caches results of the methods

查看:148
本文介绍了java缓存方法的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JMH来指定操作的复杂性。如果您从未与JMH合作过,请不要担心。 JMH将多次启动 estimateOperation 方法,然后获得平均时间。

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.

问题:[缩小] 这个程序每次会计算 Math.cbrt(Integer.MAX_VALUE)吗?或者它只计算一次然后返回缓存结果?

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

问题:[广泛]: JVM是否会缓存方法的结果?

Question: [broad]: Does JVM ever cache the result of the methods?

推荐答案

方法返回值永远不会缓存即可。但是,由于某些优化(如常量折叠常量传播),JIT编译器可能会在运行时消除 消除 em>,死代码消除循环不变提升方法内联等。

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.

例如,如果用 Math.sqrt 或用 Math替换 Math.cbrt 。 pow ,JIT编译后根本不会调用该方法,因为调用将被常量替换。 (优化不适用于 cbrt ,因为它是一种罕见的方法,它属于JVM没有内化的本机调用。)

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

这篇关于java缓存方法的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆