Вопрос

Virtual functions in C# (.NET), under-the-hood incurs an overhead of an extra method table reference, and also will never be inlined.

So, I'm wondering if in a high-performance scenario, though, its not the recommended way, is better to hide the older method with new, for better performance, and achieving JIT inlining as well.

Is this an OKAY practice?

Are there any consequences other than when retyping to a base class (which incidentally, can be 'partially' harmless in the scenario where it derives directly from an interface.

Summary:

Let me quickly summarize the comments and answers so far, below, for the benefit of others.

  1. Its almost never a good idea, compromising polymorphism and readability.
  2. Inlining does provide a signification difference in certain cases, from my tests.
  3. Research required: There's a possibility the JIT compiler might inline these virtual methods. (Possibly only under sealed classes).

Any reference to documentation, or 'inside scoop' on the behavior of the JIT compiler in this aspect would be really helpful :)

Это было полезно?

Решение

Having virtual methods is a feature. It provides additional functionality. That functionality is not free (although it is cheap). If you don't need that functionality, you can turn it off, and possibly gain some marginal performance benefits; these may or may not be enough to matter (you would need to do some performance testing to know; and of course, be warned that benchmarking microoptimizations is hard to do correctly, so be careful).

If you need the feature, and want to have polymorphic behavior, then turning it off really isn't an option. You could attempt to write your own system of virtual methods without using the language's feature, but your implementation is almost certainly going to be slower, so I would advise against it.

So in short, if you need the functionality, turn it on, if you don't, leave it off. The decision is almost certainly not going to be made based on performance considerations, but rather the requirements of the code you are writing.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top