2016-10-25

Java: About invoke bytecode instructions

You can find the Java bytecode instruction here.
  1. invokestatic: This instruction is used to call static methods on a class. It is determined at compile time, which method will be called.
  2. invokevirtual: This calls public and protected instance methods. Of course, it needs the instance reference on the stack, and also does the runtime binding (which adds overhead compared to invokestatic, but this "overhead" is not something you want to micro-optimize by design) for method dispatching. In fact, invokevirtual is not a true instruction, the actual steps taken are determined at runtime (cf. invokestatic) by the JVM, and can even involve Reflection, maybe even prohibit JIT in-place optimizations. Note, that the method handles are determined compile time, just the call path and strategy is determined at runtime (see: polymorphism).
  3. invokeinterface: Similar to invokevirtual, just the method dispatch is based on an interface, not a class.
  4. invokespecial: Calls the constructors (as they have special names that can't be referenced from plain Java code directly [on purpose]), also private and super (class parent's) methods.
  5. invokedynamic: This was introduced to address the "performance issues" of invokevirtual in a way, that the first call is executed as an invokevirtual, and the selected call path is stored for that invocation for subsequent reuse. In fact, this dynamic method resolution works with method handles obtained runtime (see: java.lang.invoke.* methods), not at compile time.
How does this affect you? Make your methods static if possible, but don't be overzealous! That's never a good approach.

No comments :

Post a Comment