Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do sealed classes really offer performance Benefits?

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 :)

like image 837
Vaibhav Avatar asked Sep 28 '22 13:09

Vaibhav


People also ask

What is the advantage of sealed class?

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.

When should you seal a class?

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.

Is Sealed class private?

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.


1 Answers

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

like image 161
Cameron MacFarland Avatar answered Oct 19 '22 16:10

Cameron MacFarland