HotSpot内联lambda函数可以调用吗? [英] Can HotSpot inline lambda function calls?

查看:84
本文介绍了HotSpot内联lambda函数可以调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑代码:

someList.forEach(x -> System.out.format("element %s", x));

从理论上讲,应该可以内联此代码并消除内联函数调用,方法是先内联forEach方法,然后在内联的forEach代码中内联lambda函数主体.

Theoretically, it should be possible to inline this code and eliminate the indirect function calls by first inlining the forEach method, and then inlining the lambda function body in the inlined forEach code.

HotSpot是否可以执行此优化?是否有限制在特定情况下执行?

Is HotSpot capable of performing this optimization? What restrictions govern whether or not it is performed in a particular situation?

推荐答案

您的lambda表达式被编译为一个普通方法,而JRE将生成一个实现功能接口并调用该方法的类.在当前的HotSpot版本中,此生成的类几乎像普通类一样工作,主要区别在于它可以调用private目标方法,并且不会被ClassLoader反向引用.

Your lambda expression is compiled into an ordinary method, while the JRE will generate a class fulfilling the functional interface and calling that method. In current HotSpot versions, this generated class works almost like an ordinary class, the main differences are that it may invoke private target methods and that it is not back-referenced by a ClassLoader.

这些属性都不妨碍优化,最后,您只有一连串普通方法调用.当前JVM中使用此类代码的最大障碍是内联限制,涉及最大深度(默认为9个嵌套方法IIRC)和最大结果代码大小.这些默认值中的一些非常旧,自上次定义以来未进行过修订.但是,这样的限制可能会影响很长的流管道,而不是像普通的forEach这样的用例.

None of these properties hinders optimizations, in the end, you only have a chain of ordinary method invocations. The biggest obstacle with such code with the current JVMs are inlining limits, regarding the maximum depth (defaults to nine nested methods IIRC) and maximum resulting code size. Some of these defaults are very old and were not revised since their last definition. However, such limits may affect very long stream pipelines, not a use case like your plain forEach.

因此,一般的答案是HotSpot能够执行此类优化,但与所有优化一样,它可以让您的代码运行几次,然后再确定其对性能是否至关重要并执行优化(如果有).

So the general answer is that HotSpot is capable of performing such optimizations, but like with all optimizations, it will let your code run a few times, before determining whether it is performance critical and perform the optimization(s), if so.

这篇关于HotSpot内联lambda函数可以调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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