Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can HotSpot inline lambda function calls?

Considering the code:

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

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.

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

like image 700
Michael Ekstrand Avatar asked May 24 '17 14:05

Michael Ekstrand


1 Answers

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.

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.

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.

like image 198
Holger Avatar answered Sep 27 '22 16:09

Holger