Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The ECMA spec states this about the <code>box</code> instruction:</p> <blockquote> <p>Stack transition: <code>..., val -&gt; ..., obj</code></p> <p>...</p> <p>If typeTok is a generic parameter, the behavior of box instruction depends on the actual type at runtime. If this type [...] is a reference type then <code>val</code> is not changed.</p> </blockquote> <p>What it's saying is that the compiler can <em>assume</em> that it's safe to <code>box</code> a reference type. So with generics, the compiler has two choices: emit the code that is guaranteed to work regardless of how the generic type is constrained, or optimize the code and omit redundant instructions where it can prove them to be unnecessary.</p> <p>The Microsoft C# compiler, in general, tends to choose the simpler approach and leave all optimization to the JIT stage. To me, it looks like your example is exactly that: not optimizing something because implementing an optimization takes time, and saving this <code>box</code> instruction probably has very little value in practice.</p> <p>C# allows even an unconstrained generic-typed value to be compared to <code>null</code>, so the compiler must support this general case. The easiest way to implement this general case is to use the <code>box</code> instruction, which does all the heavy-lifting of handling reference, value and nullable types, correctly pushing either a reference or a null value onto the stack. So the easiest thing for the compiler to do is to issue <code>box</code> regardless of the constraints, and then compare the value to zero (<code>brtrue</code>).</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.
    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