codingenious
codingenious

Reputation: 8653

Java - interface/base class reference - performance

This is general coding practice to use interface/base class reference when declaring an object like :

InterfaceIF ref = new SomeObject();

I understand that this provides loose coupling and we can change/write a new class with new implementation without affecting much code.

This is wonderfully explained here also.

But one thing which I am trying not able to understand, and is not answered on the question is :

Upvotes: 10

Views: 1807

Answers (1)

maaartinus
maaartinus

Reputation: 46392

Using the class directly may be faster, never slower. If the JVM sees a concrete class, it sort of knows "who to call". Not necessarily exactly as there may be subclasses, unless the class is final. There may be even subclasses not yet seen by the JVM which gets loaded later.

  • For a final class the method call can be optimized to the native CALL instruction. That's the trivial case.

  • If the class isn't final but there's no subclass loaded yet, it's the same with a single additional check somewhere at the beginning. When the check fails, the JVM must throw this over-optimistically compiled method away and recompile (no big deal).

  • When there are subclasses, then everything depends from how many of them were actually encountered on the given call site. If only one, then a fast check suffices to verify that the given class is the expected one (by moving this test out of loops etc., this overhead becomes negligible).

  • The cases with more candidates are obviously slower (Google for bimorphic and megamorphic).

Obviously, there's nothing what could make a call via an interface faster.

If there are multiple implementations and more than one gets called from a call site, then there's an overhead of the virtual call dispatch. For more details see this answer and this benchmark.

Upvotes: 9

Related Questions