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

后端 未结 4 1118
名媛妹妹
名媛妹妹 2021-02-08 15:03

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 disp

相关标签:
4条回答
  • 2021-02-08 15:38

    The Java Virtual Machine as of today does not care for the "final" keyword anymore (only for class assertions). Everything is considered final, unless a class is loaded which overrides the specified function, or provides another implementation of it in case of an interface.

    This results in multiple compilations of code if classes are loaded dynamically at runtime after the JIT compiler has already compiled something which it thought of as being final, but the gains seem to be wotrth the hassle.

    I don't have a link to the paper about it, but I read it some weeks ago (and maybe its just in Java 7 like this).

    0 讨论(0)
  • 2021-02-08 15:43

    The JIT-compiler cannot do this, since it is quite common to create proxies for interfaces at runtime, so the JIT-compiler can never be sure that there won't be a dynamic proxy that implements a certain interface.

    0 讨论(0)
  • 2021-02-08 15:46

    AFAIK, the JVM can in-line up to two methods, the methods doesn't have to be final. It can do this if the methods are small and called often. If your code calls three or more methods, only the most commonly called methods will be invoked.

    Note 1: The JVM does care how many implementations there are, only how many are actually called.

    Note 2: The JVM can inline methods which didn't exist at compile time, its only the code available at runtime which matters.

    0 讨论(0)
  • 2021-02-08 15:59

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

    0 讨论(0)
提交回复
热议问题