Why should one avoid initializing static fields in static constructors whenever possible?

C# has a code analysis rule enabled by default: [ CA1810 ]Initialize reference type static fields inline, it is recommended that we initialize static fields inline instead of placing initialization in static constructors.

1. The performance difference between the two initializations
2. beforefieldinit mark
3. The timing of static constructor execution
4. About the "All-Zero" structure
5. RuntimeHelpers.RunClassConstructor method

1. The performance difference between the two initializations

The CA1810 rule is related to performance. We can use the following simple code to demonstrate the performance difference between the two initializations. The static fields of both classes Foo and Bar define a static field called _value, which are initialized with the value returned by calling the static method Initialize. The difference is that Foo is initialized by inline assignment, while Bar defines the initialization operation in the static constructor. Assuming that the Initialize method is a relatively time-consuming operation, we use the _initialized field of Program to determine whether the method is called.

static class Program
{
    

Guess you like

Origin blog.csdn.net/shengyin714959/article/details/131640704