Assume I have an interface contains 3 methods namely m1(),m2(),m3() and I have an abstract class contains only abstract methods namely m1(),m2(),m3(). Assume this abstract class or interface are not going to change in future. In this case what should I prefer and why ? will it any of them has better performance?
-
4Which better performance are you looking for? Time? Memory usage? I ask because you're in the best position to measure that your self but consider if you really need to know now: https://ericlippert.com/2012/12/17/performance-rant/ – rene Jul 08 '18 at 06:08
-
Check please this post: https://stackoverflow.com/questions/7225205/performance-of-direct-virtual-call-vs-interface-call-in-c-sharp There are some links and performance tests. Common idea is that interface needs more actions, than abstract class, to resolve called method. – Hennadii Jul 08 '18 at 06:56
-
3An concrete class method that overrides an abstract method is a bit more performant than an interface implementation. The interface requires an extra hop through a stub, typically only a single JMP instruction. Very hard to see back, a nanosecond is quite difficult to profile accurately. The drastically different design implication of an interface does not make it an arbitrary choice that should be guided by perf. – Hans Passant Jul 08 '18 at 09:58
1 Answers
Write your code in the cleanest way, then profile it. If it doesn't perform as well as you would like, find the bottleneck and fix it.
Interfaces and abstract classes are different abstraction mechanisms. Abstract classes let you perform some of the work in the abstract class and call abstract methods that will need to be implemented in a derived class. Interfaces don't have any implementation (yet) but a class can implement many interfaces. If you are not implementing any behaviour, just declaring what the public shape must be, use an interface.
There is pretty much no difference in performance between invocation of an interface implementation and an abstract method override (or a virtual method override). In fact the last time I looked into this, they compiled to the same IL. Even if there was a performance difference, it would be negligible compared to the rest of your code.

- 4,319
- 1
- 22
- 20