Why are interface method invocations slower than concrete invocations?

后端 未结 6 938
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 15:24

This is question comes in mind when I finding difference between abstract class and interface. In this post I came to know that interfaces are slow as they required extra in

6条回答
  •  独厮守ぢ
    2020-11-27 15:50

    An object has a "vtable pointer" of some kind which points to a "vtable" (method pointer table) for its class ("vtable" might be the wrong terminology, but that's not important). The vtable has pointers to all the method implementations; each method has an index which corresponds to a table entry. So, to call a class method, you just look up the corresponding method (using its index) in the vtable. If one class extends another, it just has a longer vtable with more entries; calling a method from the base class still uses the same procedure: that is, look up the method by its index.

    However, in calling a method from an interface via an interface reference, there must be some alternative mechanism to find the method implementation pointer. Because a class can implement multiple interfaces, it's not possible for the method to always have the same index in the vtable (for instance). There are various possible ways to resolve this, but no way that is quite as efficient as simple vtable dispatch.

    However, as mentioned in the comments, it probably won't make much difference with a modern Java VM implementation.

提交回复
热议问题