A static constructor is executed the first time you access a static member. Knowing this, I have several questions:
[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:
static class WithConstructor {
static WithConstructor(){ }
public static int Square(int x){ return x*x; }
}
static class NoConstructor {
public static int Square(int x){ return x*x; }
}
Compiled for Release, using .NET 4.0, the results were very consistent:
╔═════════════╦══════════════════╦═════════╦═══════════════╗ ║ Iterations: ║ With Constructor ║ 4513 ms ║ Improvement: ║ ║ 1000000000 ║ No Constructor ║ 3072 ms ║ 33% ║ ╚═════════════╩══════════════════╩═════════╩═══════════════╝
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 beforefieldinit
flag must always be checked.
If a static constructor does not exist, then the method will not incur the performance hit.
Why not test it yourself?
Call your Independent method a number of times like specified above. Then make an own static class with the same method and call it the same number of times.
Use http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx for measuring.
My guess would be it won´t matter...
You could also write something to Console in your static Constructor to check if had been called. Finding out for yourself will last longer than some theroetical answer, just my 2 cents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With