title: Representing unmanaged memory
body: <p>I have a simple class that wraps around some unmanaged memory, like this:</p>
  <pre class="lang-cs prettyprint-override"><code>public class Wrapper&lt;T&gt;
  {
      private unsafe T* _ptr;
      private int _length;
  
      public int Length =&gt; _length;
  
      public unsafe Wrapper(int length)
      {
          _ptr = ...; // Assigns ptr to some pointer from unmanaged code
          _length = length;
      }
  }
  </code></pre>
  <p>Now I would like to have a way to be able to use <code>_ptr</code> safely and universally with many of <code>.NET 5</code>'s functions, so the solution to me would be to use <code>Span&lt;T&gt;</code>. However, a <code>Span</code> is allocated on the stack so I cannot cache the span.</p>
  <p>Here is what that would look like:</p>
  <pre class="lang-cs prettyprint-override"><code>public class Wrapper&lt;T&gt;
  {
      private unsafe T* _ptr;
      private int _length;
  
      public T this[int index]
      {
          get =&gt; _ptr[index]; // Works, but not very safe. Bounds checking reduces performance by 2x
          set =&gt; _ptr[index] = value;
      }
  
      // I could do this, but every time this is accessed I have to create a new span. (Like in the indexer)
      public Span&lt;T&gt; Span =&gt; new Span&lt;T&gt;(_ptr, _length); 
      public int Length =&gt; _length;
  
      public unsafe Wrapper(int length)
      {
          _ptr = ...; // Assigns ptr to some pointer from unmanaged code
          _length = length;
      }
  }
  </code></pre>
  <p>This would work well except for the fact that I also want to implement an indexer, which might be called millions of times, and that means I would have to create a <code>Span&lt;T&gt;</code> millions of times, which is not ideal for a single access.</p>
  <p>The compiler would optimize most of it out, but as I expected, not everything could be optimized out as shown by a simple benchmark.</p>
  <p>I could also use the raw <code>_ptr</code> for the indexer, but that could lead to some security issues if the caller goes out of bounds. I also simply implemented my own bounds checking, but the performance was <strong>2x</strong> worse!</p>
  <p>EDIT: <strong>I did a benchmark comparing iterating through <code>Wrapper</code> billions of times, one using a <code>Span</code> and the other indexing through a raw array, and the array performed consistently better.</strong></p>