It’s interesting question of how different constructs perform in code. And in java world and very often encountered construct is discussion about what should be used as param (or return value) in API methods. From API maintainability, extensibility, clearness etc. point of view, answer is 101% clear. Using interfaces make APIs more generic, by leaving implementation specific detail away, which allows very easily to change implementation if nececssary.

Premature optimization group, on the other hand, talks for using concrete classes in APIs since they are faster. Up to some extend that is true, but in reality in 99% of cases that performance difference is irrelevant when balanced against benefits what interfaces bring into table. Also doing microbenchmark to analyze effect is also practically futile (even if one in reference is showing some difference in special volatile access case), since JVM is doing some internal optimization for them. I remember reading from some notes in web (can’t recall & find reference right now) that that there is some look up cache, which makes performance in both cases equivalent, as long as amount of different concrete classes is same. Surely, effects of such caching are difficult to see in any microbenchmark.

Digging deeper in research finds out that there really is some smart optimization in JVM.

References:
invokevirtual vs invokeinterface performance benchmark
What is the point of invokeinterface?
HotSpotInternals: MicroBenchmarks
HotSpotInternals: InterfaceCalls
Hotspot maillist: inline cache
Wikipedia: Inline Caching
The Java Specialists’ Newsletter: Polymorphism Performance Mysteries Explained
Stackoverflow: How are java interfaces implemented internally? (vtables?)
HotSpotInternals: VirtualCalls

/ java

Vastaa

Sähköpostiosoitettasi ei julkaista. Pakolliset kentät on merkitty *

This site uses Akismet to reduce spam. Learn how your comment data is processed.