Which one is fast, Abstract class or Interface?

Furqan Safdar picture Furqan Safdar · Sep 20, 2012 · Viewed 16.9k times · Source

Possible Duplicate:
Why are interface method invocations slower than concrete invocations?

I recently had a chance to appear in an interview in which interviewer asked which one is faster among Abstract class and Interface. Though i got confused with the question but I responded Interface primarily because i thought that late binding concept can cause a performance delay in Abstract class. After exploring this same question on web, I came to know that Abstract methods are faster though according to some blogs Interface methods are faster. I was little confused so i thought to ask this question to have a correct understanding that which one is faster and why with strong reason.

According to the following the Abstract class is fast but there is no justified reason for it. http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface

Answer

flyx picture flyx · Sep 20, 2012

The answer depends on the programming language and possibly the compiler you use. In environments like the Java VM where run-time optimizations are used, it probably cannot be answered at all. And honestly, in a typical Java project, no-one cares because even if there was a difference, it would be so tiny that it won't slow down your software noticeably. Unless you have strict real-time constraints, in which case you wouldn't use Java (and possibly no polymorphism at all).

Basically, both interface methods and abstract methods make use of dynamic dispatching, so the difference is minimal if there is any at all. Without much knowledge of the details, I would assume that theoretically, abstract methods dispatch faster as long as the language doesn't implement multiple inheritance for classes. The position of the method pointer in the dispatch vector would be static, while it is not for interface methods (a class can typically implement multiple interfaces).

But as I said, I don't know the details about what happens in the compiler. There may be other factors I didn't think about. If I had to answer this question in an interview, I'd quote Don Knuth's "premature optimization is the root of all evil".