title: What is the overhead of the C# 'fixed' statement on a managed unsafe struct containing fixed arrays?
body: <p>I've been trying to determine what the true cost of using the <em>fixed</em> statement within C# for managed unsafe structs that contain fixed arrays. Please note I am not referring to unmanaged structs.</p>
  <p>Specifically, is there a reason to avoid the pattern shown by 'MultipleFixed' class below? Is the cost of simply fixing the data non zero, near zero (== cost similar to setting &amp; clearing a single flag when entering/exiting the fixed scope), or is it significant enough to avoid when possible?</p>
  <p>Obviously, these classes are contrived to help explain the question. This is for a high usage data structure in an <a href="https://en.wikipedia.org/wiki/Microsoft_XNA" rel="nofollow noreferrer">XNA</a> game where the read/write performance of this data is critical, so if I need to fix the array and pass it around everywhere I'll do that, but if there is no difference at all I'd prefer to keep the fixed() local to the methods to help with keeping the function signatures slightly more portable to platforms that don't support unsafe code. (Yeah, it’s some extra grunt code, but whatever it takes...)</p>
  <pre class="lang-csharp prettyprint-override"><code>unsafe struct ByteArray
  {
     public fixed byte Data[1024];
  }
  
  class MultipleFixed
  {
     unsafe void SetValue(ref ByteArray bytes, int index, byte value)
     {
         fixed(byte* data = bytes.Data)
         {
             data[index] = value;
         }
     }
  
      unsafe bool Validate(ref ByteArray bytes, int index, byte expectedValue)
      {
         fixed(byte* data = bytes.Data)
         {
             return data[index] == expectedValue;
         }
      }
  
      void Test(ref ByteArray bytes)
      {
          SetValue(ref bytes, 0, 1);
          Validate(ref bytes, 0, 1);
      }
  }
  
  class SingleFixed
  {
     unsafe void SetValue(byte* data, int index, byte value)
     {
         data[index] = value;
     }
  
      unsafe bool Validate(byte* data, int index, byte expectedValue)
      {
         return data[index] == expectedValue;
      }
  
      unsafe void Test(ref ByteArray bytes)
      {
          fixed(byte* data = bytes.Data)
          {
              SetValue(data, 0, 1);
              Validate(data, 0, 1);
          }
      }
  }
  </code></pre>
  <p>Also, I looked for similar questions and the closest I found was <a href="https://stackoverflow.com/questions/3323042/what-is-the-overhead-of-the-fixed-statement-when-used-on-an-unmanaged-struct">this</a>, but this question is different in that it is concerned only with pure managed code and the specific costs of using fixed in that context.</p>