Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The first time your type is accessed, the static ctor (whether generated explicitly or implicitly) has to be executed.</p> <p>When the JIT compiler compiles IL to native instructions it checks whether the static ctor for that type has been executed and if not emits native code that checks (again) whether the static ctor has been executed and if not, executes it.</p> <p>The jitted code is cached for future calls of the same method (and this is why the code had to check again if the static ctor was executed).</p> <p>The thing is, if the jitted code that checks for the static ctor is in a loop, this test will occur in every iteration.</p> <p>When beforefieldinit is present, the JIT compiler is allowed to optimize the code, by testing for the static ctor invocation BEFORE entering the loop. If it's not present, this optimization is not allowed.</p> <p>The C# compiler automatically decides for us when to emit this attribute. It currently (C# 4) emits it only if the code does NOT explicitly defines a static constructor. The idea behind it is if you defined a static ctor yourself, the timing might be more important to you and the ststic ctor should not execute ahead of time. This may or may not be true, but you can't change this behavior.</p> <p>Here is a link to the part of my online .NET tutorial that explain this in detail: <a href="http://motti.me/c1L">http://motti.me/c1L</a></p> <p>BTW, I don't recommend using static ctors on structs because believe it or not, they are not guaranteed to execute! This wasn't part of the question, so I won't elaborate, but see this for more detail if your'e interested: <a href="http://motti.me/c1I">http://motti.me/c1I</a> (I touch the subject at about 2:30 into the video).</p> <p>I hope this helps!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload