现代JVM是否可以优化简单的内联匿名类分配? [英] Does a modern JVM optimize simple inline anonymous class allocation?

查看:60
本文介绍了现代JVM是否可以优化简单的内联匿名类分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天得到了一个代码复述,将这个匿名类提取到一个字段中,以避免一遍又一遍地分配它:

I got a code review remark today to extract this anonymous class into a field, to avoid allocating it over and over again:

Collections.transform(new Function<Foo, Bar>(){
  Bar apply(Foo foo) {
    // do some simple local transform of foo into a Bar.
  }
});

我回答说,没关系,JVM会对其进行优化".尽管我知道这种优化"不会以任何方式影响性能,并且我认为使代码可以内联访问的附加价值是值得的,但我很好奇我是否对JVM优化感到好奇. 因此,我的问题是-提议的重构绝对没有操作,因为JVM仍然会对其进行优化,或者在这里有一些微小的理论性能提高?

I replied that "it doesn't matter, the JVM optimizes it". While I know for a fact that this "optimization" won't affect the performance in any way and I think the added value of having the code accessible inline is worth it, I'm curious if I was right about the JVM optimization. So, my question is - it the proposed refactoring absolutely a no-op, because the JVM will optimize it anyway, or is there some minuscule theoretical perf gain here?

推荐答案

我不会特别期望来优化它,不.

I wouldn't particularly expect it to optimize that, no.

必须确保Collections.transform不会藏匿Function,并且该方法本身也不会使this可见等.显然,所有这一切都是可行的-但是,对于在极少数情况下收益相对较小.

It would have to make sure that Collections.transform never stashed away the Function, and that the method itself never makes this visible etc. Obviously all that's doable - but it would potentially be quite a lot of work for a relatively small gain in a very few situations.

现在,如果不进行非常仔细的检查,很难说出任何特定VM的功能-但我认为这不会显着影响性能"比"JVM优化它"更为合理.

Now what any particular VM does is hard to say without very careful examination - but I think "It's not going to affect performance significantly" is a more reasonable thing to say than "The JVM optimizes it."

这篇关于现代JVM是否可以优化简单的内联匿名类分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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