[ACCEPTED]-What is the point of invokeinterface?-jvm
Each Java class is associated with a virtual method table that 28 contains "links" to the bytecode 27 of each method of a class. That table is 26 inherited from the superclass of a particular 25 class and extended with regard to the new 24 methods of a subclass. E.g.,
class BaseClass {
public void method1() { }
public void method2() { }
public void method3() { }
}
class NextClass extends BaseClass {
public void method2() { } // overridden from BaseClass
public void method4() { }
}
results in the 23 tables
BaseClass 1. BaseClass/method1() 2. BaseClass/method2() 3. BaseClass/method3() NextClass 1. BaseClass/method1() 2. NextClass/method2() 3. BaseClass/method3() 4. NextClass/method4()
Note, how the virtual method table 22 of NextClass
retains the order of entries of the 21 table of BaseClass
and just overwrites the "link" of 20 method2()
which it overrides.
An implementation of 19 the JVM can thus optimize a call to invokevirtual
by 18 remembering that BaseClass/method3()
will always be the third 17 entry in the virtual method table of any 16 object this method will ever be invoked 15 on.
With invokeinterface
this optimization is not possible. E.g.,
interface MyInterface {
void ifaceMethod();
}
class AnotherClass extends NextClass implements MyInterface {
public void method4() { } // overridden from NextClass
public void ifaceMethod() { }
}
class MyClass implements MyInterface {
public void method5() { }
public void ifaceMethod() { }
}
This 14 class hierarchy results in the virtual method 13 tables
AnotherClass 1. BaseClass/method1() 2. NextClass/method2() 3. BaseClass/method3() 4. AnotherClass/method4() 5. MyInterface/ifaceMethod() MyClass 1. MyClass/method5() 2. MyInterface/ifaceMethod()
As you can see, AnotherClass
contains the interface's 12 method in its fifth entry and MyClass
contains 11 it in its second entry. To actually find 10 the correct entry in the virtual method 9 table, a call to a method with invokeinterface
will always 8 have to search the complete table without 7 a chance for the style of optimization that 6 invokevirtual
does.
There are additional differences like 5 the fact, that invokeinterface
can be used together with 4 object references that do not actually implement 3 the interface. Therefore, invokeinterface
will have to 2 check at runtime whether a method exists 1 in the table and potentially throw an exception.
Comparing both instructions in the JVM Spec, the 3 very first difference is that invokevirtual
checks the 2 accessibility of the method during the lookup, while 1 invokeinterface
doesn't.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.