How to ensure that a call to a virtual method in a single method is looked up in the virtual function table only once?
Glavo
zjx001202 at gmail.com
Wed Oct 20 03:08:40 UTC 2021
(I am a novice in HotSpot, JIT compiler and assembly, if there is some
misunderstanding, please forgive me.)
I designed a very simple micro benchmark to test the performance of virtual
function calls (Test.java: https://paste.ubuntu.com/p/VKc57mnWgp/).
The method be tested is a very simple method:
private static void fun0(Iterator<?> it) {
while (it.hasNext()) it.next();
}
I know C2 will try to specialize the implementation for a few parameter
types to completely de virtualize, so I call it with many different
iterator types to avoid being de virtualized.
I installed hsdis for my JDK, ran it with `java
-XX:+UnlockDiagnosticVMOptions -XX:CompileCommand=print,Test::fun0
Test.java`, and got this ASM code:
https://paste.ubuntu.com/p/k2mg2svdcx/
To my great surprise, it seems that every time a virtual method is called,
it needs to be looked up in the virtual function table.
In my understanding, this is unnecessary: The parameter `it` remains
unchanged, so for calling a virtual method, we should only lookup it in the
virtual function table on the first call and cache the function pointer on
the register or stack. Each subsequent call can be made through the
function pointer without virtual call.
Unfortunately, it seems that C2 did not make this optimization for me, and
I think this will cause a noticeable performance degradation to my code.
I tried to use MethodHandle instead of virtual calls in methods, and
designed microbenchmarks using JMH. The result disappointed me. It is
always slower than making a virtual call directly.
I have some questions about this:
Will the resulting large number of virtual calls significantly degrade
function performance?
Can I use existing functions (like MethodHandle) in my code to avoid this
overhead?
Why doesn't C2 do this optimization? Because it's hard to implement?
Because there is a lot of analysis overhead? Or something else?
More information about the hotspot-dev
mailing list