C# Sealed

C# programming language

Sealed classes cannot be derived from. Does the sealed keyword improve the performance of method calls? This C# keyword prevents derivation. And it has an impact on performance in some contexts.

Keywords

Example

Class shapes

Applying the sealed keyword tells the C# compiler to apply the "sealed" metadata decoration in the assembly of your class. The sealed keyword is a syntax hint that restricts class declarations that might build on top of your sealed class.

Tip:The JIT compiler can also detect the sealed decoration and optimize method invocations better when it is used.

Next, we show an interface with one method and two classes. The first class, TestA, implements the interface but is not sealed.
The second class,
TestB,
implements the interface
and has the sealed decoration.

Program that uses sealed class: C#

using System;

/// <summary>
/// Example interface.
/// </summary>
interface ITest
{
    /// <summary>
    /// Method required by the interface.
    /// </summary>
    int GetNumber();
}

/// <summary>
/// Non-sealed class that implements an interface.
/// </summary>
class TestA : ITest
{
    /// <summary>
    /// Interface implementation.
    /// </summary>
    public int GetNumber()
    {
	return 1;
    }
}

/// <summary>
/// Sealed class that implements an interface.
/// </summary>
sealed class TestB : ITest
{
    /// <summary>
    /// Interface implementation.
    /// </summary>
    public int GetNumber()
    {
	return 2;
    }
}

class Program
{
    static void Main()
    {
	ITest test1 = new TestA(); // Regular class
	ITest test2 = new TestB(); // Sealed instantiation
	Console.WriteLine(test1.GetNumber()); // TestA.GetNumber
	Console.WriteLine(test2.GetNumber()); // TestB.GetNumber
    }
}

Output

1
2

The two classes that implement the ITest interface are slightly different. The difference is the integer-literal stored in the GetNumber method (for demonstration) and the keyword sealed stored in the TestB declarator.

Discussion

Framework: NET

What mechanism does the .NET Framework use to call interface methods and other virtual methods? Programming languages that implement class-level polymorphism store a virtual method dispatch table.

Interface

Then, the runtime looks for the method location during execution. In the .NET Framework, each type has a Type pointer on the managed heap. This is used for virtual method dispatch.

TypeJust-in-time compiler: JIT

Also, the JIT (just-in-time) optimizations in the .NET Framework are not always invoked. This depends on the execution environment. If you execute this program in the Visual Studio environment, the sealed optimization is not applied.

However:You can run the program outside of the debugger by clicking on the executable.

JIT

Benchmark

Performance optimization

I found evidence of the small but measurable speedup allowed by sealed. The benchmark shows that for the very simplest interface methods, the sealed keyword can improve performance by about a third of a nanosecond per method invocation.

Tip:For interface-heavy programs, the sealed decoration can result in a speedup on all method calls with no downside.

Outer variables used in benchmark

int sum1 = 0;
int sum2 = 0;
ITest test1 = new TestA();
ITest test2 = new TestB();

Contents of tight loops

sum1 += test1.GetNumber(); // Loop 1 body
sum1 += test1.GetNumber();
sum1 += test1.GetNumber();
sum1 += test1.GetNumber();
sum1 += test1.GetNumber();

sum2 += test2.GetNumber(); // Loop 2 body
sum2 += test2.GetNumber();
sum2 += test2.GetNumber();
sum2 += test2.GetNumber();
sum2 += test2.GetNumber();

Results

Iterations:                1000000 * 100
TestA.GetNumber (regular): 2.490 ns
TestB.GetNumber (sealed):  2.162 ns [faster]

In this benchmark, five method calls in inner loops were done together. Results take this into account and divide by 5. Stopwatch figures are converted into nanoseconds. Both methods return the value 1 in GetNumber().

StopwatchBenchmark

Tool

Program icon

There is an excellent tool developed by Vance Morrison of the .NET Runtime team, called MeasureIt. This tool provides an easy way to instantly benchmark many primitive operations on the present .NET Framework installed.

Note:Because it is an actual executable, it is always up-to-date with your current installation.

Also:The MeasureIt tool on my system reports a speedup with sealed class interface calls.

MeasureIt tool: MSDN blog

Summary

We looked at the keyword sealed in the C# language. We applied it to a class where it produced a measurable speedup on all method invocations. Sealed has performance benefits—these depend on the execution environment.


C#: Class