The static constructor is executed the first time a static member is accessed. Knowing this, I have a few questions:
- Does this mean that every time I access the static method, the runtime should check if the static constructor was called?
- Does this cause a performance failure?
- Use static constructorless classes avoiding this performance?
[EDIT] I would like to clarify that I am NOT involved in micro-optimization.
I ask this question because it is a design decision. If a static constructor strikes a performance hit, then I will design my code with this in mind and be more aware of decisions that may affect performance.
Here is an example to illustrate my question. Will there be any benefit in adopting the Independent method and putting it in a separate static class? Thus, it would not be necessary to check whether the static Test was initialized. [ Update See my answer below for a simpler, 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 is a quote from the C # spec on static constructor:
The execution of the static constructor is triggered first of the following events to occur in the application domain:
- An instance of the class is created.
- A reference to any of the static members of the class.
source share