Do sealed classes really offer performance Benefits?

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

Leave a Comment