1

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.

Engineer
  • 8,529
  • 7
  • 65
  • 105
  • `callvirt` is used either way. – CodeCaster Apr 16 '18 at 12:37
  • @CodeCaster can you provide a reference? – Engineer Apr 16 '18 at 12:37
  • https://stackoverflow.com/questions/845657/why-is-the-c-sharp-compiler-emitting-a-callvirt-instruction-for-a-gettype-meth – CodeCaster Apr 16 '18 at 12:38
  • It's just the way C# and the CLR work. Each type has a method table, whether those methods are virtual or not. – CodeCaster Apr 16 '18 at 12:38
  • @CodeCaster Hmm, not according to [this](https://stackoverflow.com/questions/193939/call-and-callvirt). Thanks for the intro to `callvirt`, helps me to search. – Engineer Apr 16 '18 at 12:39
  • 1
    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. – Hans Passant Apr 16 '18 at 12:40
  • @HansPassant Feel free to supply that as an answer to get the checkmark. Thank you. – Engineer Apr 16 '18 at 12:41
  • Too many duplicates to decide which one is best. CodeCaster's link is pretty decent, feel free to use it in your own dup vote. – Hans Passant Apr 16 '18 at 12:44
  • It's clearly a very different form of question, but as you wish. I have my answer! – Engineer Apr 16 '18 at 12:45
  • Also it might be interesting to see this talk https://www.youtube.com/watch?v=7GTpwgsmHgU where Federico Lois shared their experience of eliminating virtual calls with Generics and structs for performance reasons. – dlxeon Apr 16 '18 at 12:47

1 Answers1

1

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.

Engineer
  • 8,529
  • 7
  • 65
  • 105