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 constructer performance in C#
Class 1: Has static constructor
Time: 3208 ms
Class 2: No static constructor
Time: 319 ms
Using static constructors
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.
Class with static constructer:
/// <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;
}
}
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;
}
Notes:
Iterations: 1000000000
Details: The _text field is accessed in each iteration.
Framework: .NET 3.5 SP1
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.
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.