views:

636

answers:

5

Duplicate:

Why seal a class?

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

+9  A: 

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.

McWafflestix
+4  A: 

If the JIT compiler sees a call to a virtual method using a sealed types it can produce more efficient code by calling the method non-virtually. Now calling a non-virtual method is faster because there's no need to perform a vtable lookup. IMHO this is micro optimization that should be used as a last resort to improving performance of an application. If your method contains whatever code, the virtual version will be negligibly slower than the non-virtual compared to the cost of executing the code itself.

Darin Dimitrov
Why should this be a last resort? Why not just seal your classes by default? It's usually only considered a microopimization if there's some cost associated with it (less readable code, or more development time typically). If there's no downside to doing it, why not do it whether or not performance is an issue?
jalf
When you seal a class, you prevent use of inheritance. This can make development more difficult, it can prevent working around certain bugs. Ideally, one would think about it and design for inheritance, and make plain what is designed to be extended and seal everything else. Blindly sealing everything is too restrictive.
Eddie
+2  A: 

To extend others' answers, a sealed class (the equivalent of a final class in Java) cannot be extended. This means that any time the compiler sees a method of this class be used, the compiler knows absolutely that no runtime dispatching is needed. It does not have to examine the class to see dynamically which method of which class in the hierarchy needs to be called. This means that the branch can be compiled in rather than being dynamic.

For example, if I have a non-sealed class Animal that has a method makeNoise(), the compiler does not necessarily know whether or not any Animal instance overrides that method. Thus, each time any Animal instance invokes makeNoise(), the class hierarchy of the instance needs to be checked to see if the instance overrides this method in an extending class.

However, if I have a sealed class AnimalFeeder that has a method feedAnimal(), then the compiler knows with certainty that this method cannot be overridden. It can compile in a branch to subroutine or equivalent instruction rather than using a virtual dispatch table.

Note: You can use sealed on a class to prevent any inheritance from that class, and you can use sealed on a method that was declared virtual in a base class to prevent further overriding of that method.

Eddie
+16  A: 

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.

Reed Copsey
When designing, it may be a good idea to lean towards sealing public types that don't explicitly need to be extended since unsealing a class in a future version is a non-breaking change while the reverse is not true.
Neil Williams
@Neil Williams: I agree. In general, since unsealing a class is safe, and sealing is not, if you're making public libraries, sealing can be a nice thing to do. Again, though, this makes sealing a design choice more than a performance issue.
Reed Copsey
I thought that it was due to inlining. The C# compiler always uses callvirt because it likes the null-check side effect of that IL code.
+1  A: 

Decided to post small code samples to illustrate when C# compiler emits "call" & "callvirt" instructions.

So, here's source code of all types which I used:

    public sealed class SealedClass
    {
     public void DoSmth()
     { }
    }

    public class ClassWithSealedMethod : ClassWithVirtualMethod
    {
     public sealed override void DoSmth()
     { }
    }

    public class ClassWithVirtualMethod
    {
     public virtual void DoSmth()
     { }
    }

Also I have one method which calls all of "DoSmth()" methods:

 public void Call()
 {
  SealedClass sc = new SealedClass();
  sc.DoSmth();

  ClassWithVirtualMethod cwcm = new ClassWithVirtualMethod();
  cwcm.DoSmth();

  ClassWithSealedMethod cwsm = new ClassWithSealedMethod();
  cwsm.DoSmth();
 }

Looking on "Call()" method we can say that (theoretically) C# compiler should emit 2 "callvirt" & 1 "call" instructions, right? Unfortunately, reality is a bit different - 3 "callvirt"-s:

.method public hidebysig instance void Call() cil managed
{
    .maxstack 1
    .locals init (
        [0] class TestApp.SealedClasses.SealedClass sc,
        [1] class TestApp.SealedClasses.ClassWithVirtualMethod cwcm,
        [2] class TestApp.SealedClasses.ClassWithSealedMethod cwsm)
    L_0000: newobj instance void TestApp.SealedClasses.SealedClass::.ctor()
    L_0005: stloc.0 
    L_0006: ldloc.0 
    L_0007: callvirt instance void TestApp.SealedClasses.SealedClass::DoSmth()
    L_000c: newobj instance void TestApp.SealedClasses.ClassWithVirtualMethod::.ctor()
    L_0011: stloc.1 
    L_0012: ldloc.1 
    L_0013: callvirt instance void TestApp.SealedClasses.ClassWithVirtualMethod::DoSmth()
    L_0018: newobj instance void TestApp.SealedClasses.ClassWithSealedMethod::.ctor()
    L_001d: stloc.2 
    L_001e: ldloc.2 
    L_001f: callvirt instance void TestApp.SealedClasses.ClassWithVirtualMethod::DoSmth()
    L_0024: ret 
}

The reason is quite simple: runtime must check if type instance isn't equal to null before calling "DoSmth()" method. BUT we still can write our code in such a way that C# compiler would be able to emit optimized IL code:

 public void Call()
 {
  new SealedClass().DoSmth();

  new ClassWithVirtualMethod().DoSmth();

  new ClassWithSealedMethod().DoSmth();
 }

Result is:

.method public hidebysig instance void Call() cil managed
{
    .maxstack 8
    L_0000: newobj instance void TestApp.SealedClasses.SealedClass::.ctor()
    L_0005: call instance void TestApp.SealedClasses.SealedClass::DoSmth()
    L_000a: newobj instance void TestApp.SealedClasses.ClassWithVirtualMethod::.ctor()
    L_000f: callvirt instance void TestApp.SealedClasses.ClassWithVirtualMethod::DoSmth()
    L_0014: newobj instance void TestApp.SealedClasses.ClassWithSealedMethod::.ctor()
    L_0019: callvirt instance void TestApp.SealedClasses.ClassWithVirtualMethod::DoSmth()
    L_001e: ret 
}

If you try to call non-virtual method of non-sealed class in the same way you will also get "call" instruction instead of "callvirt"

Volodymyr Usarskyy
Thanks, why the null check is avoided in your second example? Can you please explain?
Joan Venge
Because I don't use local variable of "SealedClass" type as in first example, so compiler doesn't need to check if it's 'null'.Same IL code will be generated if you declare "SealedClass.DoSmth()" method as static
Volodymyr Usarskyy