Search code examples
c#performancestaticinstancevtable

Do non-virtual C# methods in a base class still incur vtable overheads?


Considering C# written for maximum performance, there are two ways we can have base class methods (note: we're talking about a stateless class here, no fields, only methods):

  • instance class A provides a base for inheritance / extension by class B - the usual pattern
  • static class A with static methods (pure functions) called statically by "extender" class B

I like option A because it makes the relationship clearer. What I'm wondering is, if all these base class methods are non-virtual, i.e. in the base class A they already cannot be overridden, are there vtable calls? Obviously, "non-virtual" implies no, but if there are any overheads, I'd like to know.


Solution

  • According to @HansPassant (many thanks),

    Even non-virtual calls to an instance method are made with the exact equivalent of a virtual call. Giving up a bit of perf for a very nice guarantee, a NullReferenceException is always raised at the call site. Diagnosing NRE when this is null is quite ugly.

    Only a call to a static method is non-virtual. That includes extension methods btw.