A static constructor is executed the first time you access a static member. Knowing this, I have several questions:
- Does this mean that every time I access a static method, the runtime must check if the static constructor has been called?
- Does this incur a performance hit?
- Do “constructor-less” static classes avoid this performance hit?
[EDIT]: I would like to clarify that I’m NOT concerned with micro-optimization.
I am asking this question because it is a design decision. If a static constructor incurs a performance hit, then I will design my code with that in mind, and will be more aware of the decisions that may affect performance.
Here’s an example to illustrate my question. Would there be any benefit of taking the Independent method and putting it in a separate static class? That way, it would not have to check if static Test had been initialized. [Update See my answer below for a better, simpler example].
static class Test {
// Static constructor with dependent method:
static int x;
static Test() { x = 5; }
static int Dependent() { return x; }
// Static, independent method:
static int Independent(int y) { return y+1; }
}
Here’s the quote from the C# specification about the static constructor:
The execution of a static constructor is triggered by the first of the
following events to occur within an application domain:
- An instance of the class is created.
- Any of the static members of the class are referenced.
Due to the lack of answers, and under @Jobo’s direction, I decided to test this for myself.
Here are my test classes:
Compiled for Release, using .NET 4.0, the results were very consistent:
Therefore, I’m going to answer my own questions:
If a static constructor exists, then a static method will incur a (microscopic) performance hit, because the
beforefieldinitflag must always be checked.If a static constructor does not exist, then the method will not incur the performance hit.