Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are sealed types faster?

Why are sealed types faster?

I am wondering about the deeper details about why this is true.

like image 560
Joan Venge Avatar asked May 26 '09 16:05

Joan Venge


People also ask

Are Sealed classes faster?

sealed classes will be at least a tiny bit faster, but sometimes can be waayyy faster... if the JIT Optimizer can inline calls that would have otherwise been virtual calls. So, where there's oft-called methods that are small enough to be inlined, definitely consider sealing the class.

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.

Why do we use sealed classes in C#?

We use sealed classes to prevent inheritance. As we cannot inherit from a sealed class, the methods in the sealed class cannot be manipulated from other classes. It helps to prevent security issues.


2 Answers

At the lowest level, the compiler can make a micro-optimization when you have sealed classes.

If you're calling a method on a sealed class, and the type is declared at compile time to be that sealed class, the compiler can implement the method call (in most cases) using the call IL instruction instead of the callvirt IL instruction. This is because the method target can not be overridden. Call eliminates a null check and does a faster vtable lookup than callvirt, since it doesn't have to check virtual tables.

This can be a very, very slight improvement to performance.

That being said, I would completely ignore that when deciding whether to seal a class. Marking a type sealed really should be a design decision, not a performance decision. Do you want people (including yourself) to potentially subclass from your class, now or in the future? If so, do not seal. If not, seal. That really should be the deciding factor.

like image 110
Reed Copsey Avatar answered Oct 03 '22 18:10

Reed Copsey


Essentially, it's got to do with the fact that they don't need to have to worry about extensions to a virtual function table; the sealed types can't be extended, and therefore, the runtime doesn't need to be concerned about how they may be polymorphic.

like image 32
Paul Sonier Avatar answered Oct 03 '22 18:10

Paul Sonier