Search code examples
c#c++polymorphismvirtual

Speed of virtual call in C# vs C++


I seem to recall reading somewhere that the cost of a virtual call in C# is not as high, relatively speaking, as in C++. Is this true? If so - why?


Solution

  • A C# virtual call has to check for “this” being null and a C++ virtual call does not. So I can’t see in generally why a C# virtual calls would be faster. In special cases the C# compiler (or JIT compiler) may be able to inline the virtual call better then a C++ compiler, as a C# compiler has access to better type information. The call method instruction may sometimes be slower in C++, as the C# JIT may be able to use a quicker instruction that only copes with a small offset as it know more about the runtime memory layout and processor model then a C++ compiler.

    However we are talking about a handful of processor instruction at most here. On a modem superscalar processor, it is very possible that the “null check” instruct is run at the same time as the “call method” and therefore takes no time.

    It is also very likely that all the processor instructions will already in be the level 1 cache if the call is make in a loop. But the data is less likely to be caches, the cost of reading a data value from main memory these days is the same as running 100s of instructions from the level 1 cache. Therefore it is unlucky that in real applications the cost of a virtual call is even measurable in more then a very few places.

    The fact that the C# code uses a few more instructions will of course reduce the amount of code that can fit in the cache, the effect of this is impossible to predict.

    (If the C++ class uses multiple inherence then the cost is more, due to having to patch up the “this” pointer. Likewise interfaces in C# add another level of redirection.)