title: Allocation-free List<T>-like small data struct for .NET 5+
body: <p>Are there any data structures for .NET (the recent versions) that have an initial &quot;small&quot; mode that doesn't allocate memory? Something that would use initially memory on the stack (stackalloc), then if that is all used up switch to using the heap and only then put pressure on GC. A <code>SmallList&lt;T&gt;</code> with a a similar interface to <code>List&lt;T&gt;</code> would be the most useful when you know in most cases only a few items are added.</p>
  <p>In C++ there is at least one good implementation of this idea used in LLVM, the SmallVector and some similar small types for sets/maps.
  <a href="https://stackoverflow.com/questions/42122054/what-is-the-difference-between-stdvector-and-llvmsmallvector-which-one-to-u">What is the difference between std::vector and llvm::SmallVector? which one to use when?</a><br />
  Also this video: <a href="https://www.youtube.com/watch?v=vElZc6zSIXM" rel="nofollow noreferrer">CppCon 2016: Chandler Carruth “High Performance Code 201: Hybrid Data Structures&quot;</a></p>
  <p>I've been googling a bit and couldn't find anything about an existing implementation, and if it's even possible to do. It would have to be limited to value types more than certainly, but even then not sure how you would write some T value into the stackalloc array and read it back - for ex. if T is an int, is there now an API to &quot;reinterpret_cast&quot; a range of bytes from a span to an int directly, not by combining the 4 bytes one by one?</p>
  <p>The closest data-struct with this idea I could find is the SStringBuilder from the Towel lib:
  <a href="https://github.com/ZacharyPatten/Towel/blob/main/Sources/Towel/SStringBuilder.cs" rel="nofollow noreferrer">https://github.com/ZacharyPatten/Towel/blob/main/Sources/Towel/SStringBuilder.cs</a></p>
  <pre><code>// SStringBuilder is a small helper for initializing strings.
  // It will append to the span until the capacity is reached
  // and then it will revert to a StringBuilder if necessary
  </code></pre>
  <hr />
  <p><strong>Edit</strong><br />
  Found this API, may be what's needed
  <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal.read?view=net-6.0#system-runtime-interopservices-memorymarshal-read-1(system-readonlyspan((system-byte)))" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal.read</a></p>
  <hr />
  <p><strong>Edit 2</strong></p>
  <p>Made a hacky SmallList that just works with the small number of values, throwing an exception if capacity is reached instead of switching to a List. Tried a few ways of doing this:</p>
  <ul>
  <li>with Span and using MemoryMarshal.Read/Write</li>
  <li>with Span and read/write directly the span</li>
  <li>with ArrayPool.Shared.Rent/Return</li>
  <li>with a List</li>
  <li>with a List with capacity preallocated in constructor</li>
  </ul>
  <p>Up to close to 32 values, the Span versions are quite a lot faster, below are some results from BenchmarkDotNet - bench just adds N small structs (2 int fields) to the list and then gets each value and adds up the fields. N was 1,2,4... and a few more up to 128, was curious at what point the advantage disappears, in practice the stack part should be for &lt; 10 values.</p>
  <pre><code>Results for 2 values:
  |         SpanListBench |      2 |   6.126 ns | 0.0188 ns | 0.0147 ns |
  |   TypedSpanlListBench |      2 |   5.403 ns | 0.0147 ns | 0.0123 ns |
  |         PoolListBench |      2 |  24.182 ns | 0.0375 ns | 0.0351 ns |
  |             ListBench |      2 |  18.160 ns | 0.1737 ns | 0.1540 ns |
  |     ListBenchPrealloc |      2 |  13.754 ns | 0.0978 ns | 0.0867 ns |
  </code></pre>
  <pre><code>Results for 8 values:
  |        SpanListBench  |      8 |  18.045 ns | 0.0494 ns | 0.0438 ns |
  |    TypedSpanListBench |      8 |  16.467 ns | 0.0565 ns | 0.0472 ns |
  |         PoolListBench |      8 |  31.558 ns | 0.0735 ns | 0.0651 ns |
  |             ListBench |      8 |  44.527 ns | 0.1977 ns | 0.1849 ns |
  |     ListBenchPrealloc |      8 |  29.989 ns | 0.2079 ns | 0.1736 ns |
  </code></pre>
  <pre><code> ref struct TypedSpanList&lt;T&gt; where T:struct
      {
          private Span&lt;T&gt; buffer_;
          private int count_;
  
          public TypedSpanList(Span&lt;T&gt; buffer)
          {
              buffer_ = buffer;
              count_ = 0;
          }
  
          [MethodImpl(MethodImplOptions.AggressiveInlining)]
          public void Add(T value)
          {
              if (count_ &gt;= buffer_.Length)
              {
                  throw new InvalidOperationException();
              }
              buffer_[count_] = value;
              count_++;
          }
  
          [MethodImpl(MethodImplOptions.AggressiveInlining)]
          public T Get(int index)
          {
              if (index &gt;= buffer_.Length)
              {
                  throw new InvalidOperationException();
              }
              return buffer_[index];
          }
      }
  
          [Benchmark]
          public  int TypedListBench()
          {
              int count = 0;
              Span&lt;Test&gt; s = stackalloc Test[Number];
              var sl = new TypedSpanList&lt;Test&gt;(s);
  
              for (int i = 0; i &lt; Number; i++)
              {
                  sl.Add(new Test() { a = i, b = i + 1 });
              }
  
              for (int i = 0; i &lt; Number; i++)
              {
                  var t = sl.Get(i);
                  count += t.a + t.b;
              }
  
              return count;
          }
  </code></pre>
  <hr />