MethodHandle performance

不想你离开。 提交于 2019-12-03 05:52:23
NightDweller

Looks like this was indirectly answered by @AlekseyShipilev in reference to a different query. In the following link How can I improve performance of Field.set (perhap using MethodHandles)?

If you read through you will see additional benchmarks that show similar findings. It is likely that direct calls can simply be optimized by JIT in ways that According to the findings above, the difference is: MethodHandle.invoke =~195ns MethodHandle.invokeExact =~10ns Direct calls = 1.266ns

So - direct calls will still be faster, but MH is very fast. For most use-cases this should be sufficient and is certainly faster than the old reflection framework (btw - according to the findings above, reflection is also significantly faster under java8 vm)

If this difference is significant in your system, i would suggest finding different patterns rather than direct reflection which will support direct calls.

mentics

It appears others have seen similar results: http://vanillajava.blogspot.com/2011/08/methodhandle-performance-in-java-7.html

Here's someone else's: http://andrewtill.blogspot.com/2011/08/using-method-handles.html

I ran that second one and saw they were about the same speed even fixing that test to have a warmup. However, I fixed it so it wasn't creating an args array every time. At the default count, it resulted in the same result: methodhandles were a little faster. But I did a count of 10000000 (default*10) and reflection went much faster.

So, I would recommend testing with parameters. I wonder if MethodHandles more efficiently deal with parameters? Also, check changing the count--how many iterations.

@meriton's comment on the question links to his work and looks very helpful: Calling a getter in Java though reflection: What's the fastest way to repeatedly call it (performance and scalability wise)?

If the publicStaticMethod was a simple implementation like returning a constant, It is very much possible that direct call was in-lined by JIT compiler. This may not be possible with methodHandles.

RE http://vanillajava.blogspot.com/2011/08/methodhandle-performance-in-java-7.html example, as mentioned that comments its not great implementation. if you change the type casting to int (instead of Integer) in the calculation loop, the results are closer to direct method call.

With convoluted implementation of ( creating and calling a future task which returns a random int) gave benchmark with closer numbers where MethodStatic was max ~10% slower than direct method. So you might be seeing 3 times slower performance due to JIT optimizations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!