Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java optimize method calls via an interface which has a single implementor marked as final?

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?

like image 898
Uri Avatar asked Jun 10 '09 03:06

Uri


1 Answers

(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.

like image 194
Eugene Yokota Avatar answered Oct 19 '22 16:10

Eugene Yokota