I have come across a lot of optimization tips which say that you should mark your classes as sealed to get extra performance benefits.
I ran some tests to check the performance differential and found none. Am I doing something wrong? Am I missing the case where sealed classes will give better results?
Has anyone run tests and seen a difference?
Help me learn :)
Sealed classes prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.
The main purpose of a sealed class is to take away the inheritance feature from the class users so they cannot derive a class from it. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.
A Private class can only be accessed by the class it is defined and contain within - it is completely inaccessible to outside classes. A Sealed class can be accessed by any class, but can not be derived from.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With