If I have a reference to a class and invoke a method on it, and the class or the method is final, my understanding is that the compiler or the JVM would replace the dynamic dispatch with a cheaper static dispatch since it can determine exactly which version would be invoked.
However, what if I have a reference to an interface, and the interface currently has only a single implementor, and that implementor is final or the method is final in that implementor, can the JVM figure that out at runtime and optimize these calls?
(Insert Knuth quote here about optimization.)
See Wikis Home > HotSpot Internals for OpenJDK > PerformanceTechniques.
- Methods are often inlined. This increases the compiler's "horizon" of optimization.
- Static, private, final, and/or "special" invocations are easy to inline.
- Virtual (and interface) invocations are often demoted to "special" invocations, if the class hierarchy permits it. A dependency is registered in case further class loading spoils things.
- Virtual (and interface) invocations with a lopsided type profile are compiled with an optimistic check in favor of the historically common type (or two types).
There are some interesting links from Inlining.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With