2

I read about sealed class and know that a sealed class cannot be inherited.

If i decorate class with sealed when i don't need inherited from the sealed class,do i get more performance?

// cs_sealed_keyword.cs
// Sealed classes
using System;
sealed class MyClass 
{
   public int x; 
   public int y;
}

class MainClass 
{
   public static void Main() 
   {
      MyClass mC = new MyClass(); 
      mC.x = 110;
      mC.y = 150;
      Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); 
   }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

3

Once upon a time, in the early days of OO, non-virtual methods afforded a noticeable performance benefit by avoiding a vtable access. Nowadays, however, the rationale behind the sealed modifier is far more about design choices, controlling how client code interacts with your library.

Just as marking a method private allows you to reserve implementation details for future improvement, marking a class sealed gives you a guarantee that (barring shady Reflection shenanigans) users of your library will not be able to interpose their code into your call graph in unexpected, possibly disastrous ways by unwisely subclassing your implementation.

This is particularly vital in security situations, where a tightly-controlled class structure could be completely undone by a single interloper subclass. Thus, you'll find a significant number of sealed classes in the System.Security namespaces.

Eric Lloyd
  • 509
  • 8
  • 19
0

There is a very little performance improvement when a sealed modifier is used. The compiler does the micro optimization at the lowest level.

JIT compiler can produce more efficient code by calling the method non-virtually

Also check out this Thread

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331