Can HotSpot build in lambda function?

Given the code:

someList.forEach(x -> System.out.format("element %s", x)); 
Theoretically, it should be possible to embed this code and eliminate indirect function calls by first inserting the forEach method and then inserting the body of the lambda function into the inlined forEach code.

Can HotSpot perform this optimization? What restrictions determine whether this is done in a particular situation?

+5
source share
2 answers

Your lambda expression is compiled into a regular method, while the JRE will generate a class that executes a functional interface and calls this method. In existing versions of HotSpot, this generated class works almost like a regular class, the main differences are that it can call private target methods and that it does not reference the ClassLoader .

None of these properties prevent optimization; after all, you only have a chain of regular method calls. The biggest hurdle for this code with current JVMs is the maximum depth limit (by default, nine nested IIRC methods) and the maximum resulting code size. Some of these defaults are very old and have not been reviewed since they were last determined. However, such restrictions can affect very long stream pipelines, and not on usage, for example, on your regular forEach .

Thus, the general answer is that HotSpot is able to perform such optimizations, but, like with all optimizations, it will run your code several times before determining whether it is performance critical and performs optimization (s) if This is true.

+4
source

This is actually really easy to prove. Here is a very simple code:

  for (int i = 0; i < 100_000; ++i) { Stream.of(1, 2, 3, 4) .map(x -> x * 2) .collect(Collectors.toList()); } 

When I compile this, I see that the generated de-sugared method (via javap ) for the lambda expression is called: lambda$main$0 (in jdk-9, but that doesn't really matter).

And then I can just run this code with:

  java -XX:-TieredCompilation -XX:CICompilerCount=1 -XX:+UnlockDiagnosticVMOptions -XX:+PrintCompilation -XX:+PrintInlining -XX:CompileCommand="print, *.lambda" InlineLambdaTest > inline.txt 

And looking at the file, there are lines like this:

  Inline::lambda$main$0 (10 bytes) inline (hot) 

Thus, inlay for such a method works in the usual way. Note that there will be more lines starting with ...lambda... since there are many other places inside that use a lambda expression that are also considered hot.

+3
source

Source: https://habr.com/ru/post/1268179/


All Articles