Do sealed classes really offer performance Benefits?
The JITter will sometimes use non-virtual calls to methods in sealed classes since there is no way they can be extended further.
There are complex rules regarding calling type, virtual/nonvirtual, and I don't know them all so I can't really outline them for you, but if you google for sealed classes and virtual methods you might find some articles on the topic.
Note that any kind of performance benefit you would obtain from this level of optimization should be regarded as last-resort, always optimize on the algorithmic level before you optimize on the code-level.
Here's one link mentioning this: Rambling on the sealed keyword
The answer was no, sealed classes do not perform better than non-sealed.
2021: The answer is now yes there are performance benefits to sealing a class.
Sealing a class may not always provide a performance boost, but the dotnet team are adopting the rule of sealing all internal classes to give the optimiser the best chance.
For details you can read https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-6/#peanut-butter
Old answer below.
The issue comes down to the call
vs callvirt
IL op codes. Call
is faster than callvirt
, and callvirt
is mainly used when you don't know if the object has been subclassed. So people assume that if you seal a class all the op codes will change from calvirts
to calls
and will be faster.
Unfortunately callvirt
does other things that make it useful too, like checking for null references. This means that even if a class is sealed, the reference might still be null and thus a callvirt
is needed. You can get around this (without needing to seal the class), but it becomes a bit pointless.
Structs use call
because they cannot be subclassed and are never null.
See this question for more information:
Call and callvirt