C# Static Constructor

You want to determine the performance hit for static constructors in the C# programming language. Microsoft and many developers warn that static constructors on a type impose a substantial overhead. Static constructors are also called type initializers, because they refer to types, not instances. Here we test static constructors in the C# language and determine if they are useful.

=== Static constructor performance test in C# ===

Class 1: Has static constructor
Time:    3208 ms

Class 2: No static constructor
Time:    319 ms

Using static constructors

Here we see an example class with a static constructor, and also an example class without. Most classes you use will likely not have static constructors. The author's results were that static constructors do cause a slowdown of all accesses to the type. Note that instances are not the same as types, in that instances are specific objects of the type.

=== Example class with static constructor ===

/// <summary>
/// This type has a static constructor
/// </summary>
static class HasStaticConstructor
{
    /// <summary>
    /// Public field
    /// </summary>
    public static int _test;

    /// <summary>
    /// Static constructor initializes public field
    /// </summary>
    static HasStaticConstructor()
    {
        _test = 1;
    }
}

=== Example class without static constructor ===

/// <summary>
/// This type has no static constructor
/// </summary>
static class NoStaticConstructor
{
    /// <summary>
    /// Public field initialized inline
    /// </summary>
    public static int _test = 1;
}

=== Benchmark notes ===

Iterations: 1000000000
Details:    The _text field is accessed in each iteration.
Framework:  .NET 3.5 SP1

Description of code. What the code does is compare a class that has a static, type constructor against one that does not. In the first class, which has the static constructor, the static field _test is initialized in the constructor.

Class without static constructor. In the second class, which has no static constructor, the _test field is initialized inline, meaning directly in the declaration. This has the same effect on behavior.

Summary

Here we saw that static constructors might be convenient, but that they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. It is appropriate to use a lazy instantiation pattern sometimes, meaning you check a field for null in an accessor each time it is accessed, and if it is null, you can initialize it.

See Class Overview.

See Static Overview.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen