An excerpt from the stairway book:
If efficiency is very important, lean towards using a class. Most Java
runtimes make a virtual method invocation of a class member a faster operation
than an interface method invocation. Traits get compiled to interfaces
and therefore may pay a slight performance overhead. However, you should
make this choice only if you know that the trait in question constitutes a performance
bottleneck and have evidence that using a class instead actually
solves the problem.
I wrote some simple code to see what really happens behind the scenes. And I did notice invokevirtual being used in case of an abstract class and invokeinterface in case of an interface.
But no matter what kind of code I wrote they always roughly performed the same. I use HotSpot 1.6.0_18 in server mode.
Is it JIT doing such a great job optimizing?
Does anybody have a sample code which proves the claim from the book about invokevirutal being the faster operation?
If HotSpot notices that all instances at the call site are of the same type, it is able to use a monomorphic method call and both virtual and interface methods are optimized the same way. The documents PerformanceTechniques and VirtualCalls make no distinction between virtual and interface methods.
But in the general non-monomorphic case there might be some difference. The InterfaceCalls document says:
It also confirms that the monomorphic case is the same for both:
Other JVMs might have different optimizations.
You could try a micro benchmark (if you know how) which calls methods on multiple classes which implement the same interface, and on multiple classes which extend the same abstract class. That way it should be possible to force the JVM to use non-monomorphic method calls. (Though in the real life any difference there might not matter, since most calls sites are anyways monomorphic.)