Report an example of performance degradation that occurred when the argument Comparator of Arrays.sort was given by a lambda expression

When answering NumberOfDiscIntersections of Lesson 6 of Codility in Java, we confirmed the phenomenon that performance deteriorates when using lambda expression. I shared it.

** Note: Below, examples of answers to the above questions are included in the GitHub link. ** **

When using lambda expression

In the first answer, I used a lambda expression as follows. Source code when using lambda expression

The result is as follows. performance.png

When N is large, it is confirmed that the performance score does not meet the criteria.

When using anonymous class

While trying to improve the performance and making trial and error, I modified it to use the anonymous class from the lambda expression as follows. Fixed to use anonymous class

The result is as follows. kaizen.png

Although it is in milliseconds, it is confirmed that the performance is improved.

Results and discussion

It turns out that using lambda expressions can result in poor performance compared to using anonymous classes. This suggests that ** in cases where performance is severely required, a performance regression test may also be required when refactoring using a lambda expression **.

If you search the Internet for related information, for example, [How different is the performance of each Java writing style? I compared the measurements. Stream and loops-Qiita](https://qiita.com/ota-meshi/items/40d5dcb0e99574a8a368#%E3%83%A9%E3%83%A0%E3%83%80%E5%BC%8F%E3 % 81% A8% E5% 8C% BF% E5% 90% 8D% E3% 82% AF% E3% 83% A9% E3% 82% B9), the performance is improved by the lambda expression, or there is no difference. ,it is written like this. But Java: Lambda is slow? --Development notes states that lambda expressions degrade performance. According to Lambda and invokedynamic honeymoon, the factors that increase the execution time of anonymous classes are I / O and jar decompression. It is considered that the factors that increase the execution time of the lambda expression are the bootstrap method call and the bytecode generation, and the sum of the former is smaller than the sum of the latter (link page 38).

In this case, the anonymous class was not measured because the class was generated before execution, while the performance of the lambda class deteriorated by that amount because the class was generated at runtime. it is conceivable that.

... Honestly, I'm not very confident, so if you have any suggestions, I would appreciate it if you could teach me.

Recommended Posts

Report an example of performance degradation that occurred when the argument Comparator of Arrays.sort was given by a lambda expression
The story that the performance increased by 9.26 times when the layout method of View was changed from AutoLayout to warm hand calculation.
[Docker] List of errors that occurred when building the environment