Using Span<T> To Improve Performance Of C# Code

In my experience, the main thing to do in order to improve application performance is to reduce the number and duration of IO-calls. However, once this option is exercised another path that developers take is using memory on stack. Stack allows very fast allocation and deallocation although it should be used only for allocating small portions since stack size is pretty small. Also, using stack allows for reducing pressure on GC. In order to allocate memory on stack, one uses value types or stackalloc operator combined with the usage of unmanaged memory.
The second option is rarely used by developers since API for unmanaged memory access is quite verbose.
Span<T> is a family of value types that arrived in C# 7.2 which is an allocation-free representation of memory from different sources. Span<T> allows developers to work with regions of contiguous memory in more convenient fashion ensuring memory and type safety.

Span implementation

Ref return
The first step in wrapping your head around Span<T> implementation for those who don’t closely follow updates in C# language is learning about ref returns which were introduced in C# 7.0.
While most of the readers are familiar with passing method argument by reference, now C# allows returning a reference to a value instead of the value itself.
Let us examine how it works. We’ll create a simple wrapper around an array of prominent musicians which exhibits both traditional behavior and new ref return feature.
  1. public class ArtistsStore  
  2. {  
  3.     private readonly string[] _artists = new[] { "Amenra""The Shadow Ring""Hiroshi Yoshimura" };  
  5.     public string ReturnSingleArtist()  
  6.     {  
  7.         return _artists[1];  
  8.     }  
  10.     public ref string ReturnSingleArtistByRef()  
  11.     {  
  12.         return ref _artists[1];  
  13.     }  
  15.     public string AllAritsts => string.Join(", ", _artists);  
  16. }  
Now let’s call those methods
  1. var store = new ArtistsStore();  
  2. var artist = store.ReturnSingleArtist();  
  3. artist = "Henry Cow";  
  4. var allArtists = store.AllAritsts; //Amenra, The Shadow Ring, Hiroshi Yoshimura  
  6. artist = store.ReturnSingleArtistByRef();  
  7. artist = "Frank Zappa";  
  8. allArtists = store.AllAritsts; //Amenra, The Shadow Ring, Hiroshi Yoshimura  
  10. ref var artistReference = ref store.ReturnSingleArtistByRef();  
  11. artistReference = "Valentyn Sylvestrov";  
  12. allArtists = store.AllAritsts; //Amenra, Valentyn Sylvestrov, Hiroshi Yoshimura  
Observe that while in the first and the second example original collection is unmodified. In the final example we’ve managed to alter the second artist of the collection. As you’ll see later during the course of the article this useful feature will help us operate arrays located on the stack in a reference-like fashion.
Ref structs
As we know, value types might be allocated on stack. Also, they don't necessarily depend on the context where the value is used. In order to make sure that the value is always allocated on stack the concept of ref struct was introduced in C# 7.0. Span<T> is a ref struct so we are sure that is always allocated on stack.
Span implementation
Span<T> is a ref struct which contains a pointer to memory and length of the span similar to below.
  1. public readonly ref struct Span<T>  
  2. {  
  3.   private readonly ref T _pointer;  
  4.   private readonly int _length;  
  5.   public ref T this[int index] => ref _pointer + index;  
  6.   ...  
  7. }  
Note ref modifier near the pointer field. Such construct can’t be declared in a plain C# in .NET Core it is implemented via ByReference<T>.
So as you can see indexing is implemented via ref return which allows reference-type-like behavior for stack-only struct.

Span limitations

To ensure that the ref struct is always used on the stack it possesses a number of limitations; i.e.,they can’t be boxed, they can’t be assigned to variables of type object, dynamic or to any interface type, they can’t be fields in a reference type, and they can’t be used across await and yield boundaries. In addition, calls to two methods, Equals and GetHashCode, throw a NotSupportedException. Span<T> is a ref struct.

Using Span instead of string

Reworking existing codebase.
Let’s examine code that converts Linux permissions to octal representation. You can access it here. Here is the original code
  1. internal class SymbolicPermission  
  2. {  
  3.     private struct PermissionInfo  
  4.     {  
  5.         public int Value { getset; }  
  6.         public char Symbol { getset; }  
  7.     }  
  9.     private const int BlockCount = 3;  
  10.     private const int BlockLength = 3;  
  11.     private const int MissingPermissionSymbol = '-';  
  13.     private readonly static Dictionary<int, PermissionInfo> Permissions = new Dictionary<int, PermissionInfo>() {  
  14.             {0, new PermissionInfo {  
  15.                 Symbol = 'r',  
  16.                 Value = 4  
  17.             } },  
  18.             {1, new PermissionInfo {  
  19.                 Symbol = 'w',  
  20.                 Value = 2  
  21.             }},  
  22.             {2, new PermissionInfo {  
  23.                 Symbol = 'x',  
  24.                 Value = 1  
  25.             }} };  
  27.     private string _value;  
  29.     private SymbolicPermission(string value)  
  30.     {  
  31.         _value = value;  
  32.     }  
  34.     public static SymbolicPermission Parse(string input)  
  35.     {  
  36.         if (input.Length != BlockCount * BlockLength)  
  37.         {  
  38.             throw new ArgumentException("input should be a string 3 blocks of 3 characters each");  
  39.         }  
  40.         for (var i = 0; i < input.Length; i++)  
  41.         {  
  42.             TestCharForValidity(input, i);  
  43.         }  
  45.         return new SymbolicPermission(input);  
  46.     }  
  48.     public int GetOctalRepresentation()  
  49.     {  
  50.         var res = 0;  
  51.         for (var i = 0; i < BlockCount; i++)  
  52.         {  
  53.             var block = GetBlock(i);  
  54.             res += ConvertBlockToOctal(block) * (int)Math.Pow(10, BlockCount - i - 1);  
  55.         }  
  56.         return res;  
  57.     }  
  59.     private static void TestCharForValidity(string input, int position)  
  60.     {  
  61.         var index = position % BlockLength;  
  62.         var expectedPermission = Permissions[index];  
  63.         var symbolToTest = input[position];  
  64.         if (symbolToTest != expectedPermission.Symbol && symbolToTest != MissingPermissionSymbol)  
  65.         {  
  66.             throw new ArgumentException($"invalid input in position {position}");  
  67.         }  
  68.     }  
  70.     private string GetBlock(int blockNumber)  
  71.     {  
  72.         return _value.Substring(blockNumber * BlockLength, BlockLength);  
  73.     }  
  75.     private int ConvertBlockToOctal(string block)  
  76.     {  
  77.         var res = 0;  
  78.         foreach (var (index, permission) in Permissions)  
  79.         {  
  80.             var actualValue = block[index];  
  81.             if (actualValue == permission.Symbol)  
  82.             {  
  83.                 res += permission.Value;  
  84.             }  
  85.         }  
  86.         return res;  
  87.     }  
  88. }  
  90. public static class SymbolicUtils  
  91. {  
  92.     public static int SymbolicToOctal(string input)  
  93.     {  
  94.         var permission = SymbolicPermission.Parse(input);  
  95.         return permission.GetOctalRepresentation();  
  96.     }  
  97. }  
The reasoning is pretty straightforward: string is an array of char, so why not allocate it on stack instead of heap.
So our first goal is to mark field _value of SymbolicPermission as ReadOnlySpan<char> instead of string. To achieve this we must declare SymbolicPermission as ref struct since field or property cannot be of type Span<T> unless it’s an instance of a ref struct.
  1. internal ref struct SymbolicPermission  
  2. {  
  3.     ...  
  4.     private ReadOnlySpan<char> _value;  
  5. }  
Now we just change every string within our reach to ReadOnlySpan<char>. The only point of interest is GetBlock method since here we replace Substring with Slice.
  1. private ReadOnlySpan<char> GetBlock(int blockNumber)  
  2. {  
  3.     return _value.Slice(blockNumber * BlockLength, BlockLength);  
  4. }  


Let’s measure the outcome.
We notice the speed up which accounts for 50 nanoseconds which is about 10% of performance improvement. One can argue that 50 nanoseconds are not that much but it costed almost nothing for us to achieve it!
Now we’re going to evaluate this improvement on permission having 18 blocks of 12 characters each to see whether we can gain significant improvements.
As you can see we’ve managed to gain 0.5 microsecond or 5% performance improvement. Again it may look like a modest achievement. But remember that this was really low hanging fruit.

Using Span instead of arrays

Let’s expand on arrays of other types. Consider the example from ASP.NET Channels pipeline. The reasoning behind the code below is that data often arrives in chunks over the network which means that the piece of data may reside in multiple buffers simultaneously. In the example such data is parsed to int.
  1. public unsafe static uint GetUInt32(this ReadableBuffer buffer) {  
  2.     ReadOnlySpan<byte> textSpan;  
  4.     if (buffer.IsSingleSpan) { // if data in single buffer, it’s easy  
  5.         textSpan = buffer.First.Span;  
  6.     }  
  7.     else if (buffer.Length < 128) { // else, consider temp buffer on stack  
  8.         var data = stackalloc byte[128];  
  9.         var destination = new Span<byte>(data, 128);  
  10.         buffer.CopyTo(destination);  
  11.         textSpan = destination.Slice(0, buffer.Length);  
  12.     }  
  13.     else {  
  14.         // else pay the cost of allocating an array  
  15.         textSpan = new ReadOnlySpan<byte>(buffer.ToArray());  
  16.     }  
  18.     uint value;  
  19.     // yet the actual parsing routine is always the same and simple  
  20.     if (!Utf8Parser.TryParse(textSpan, out value)) {  
  21.         throw new InvalidOperationException();  
  22.     }  
  23.     return value;  
  24. }  
Let’s break it down a bit about what happens here. Our goal is to parse the sequence of bytes textSpan into uint.
  1. if (!Utf8Parser.TryParse(textSpan, out value)) {  
  2.     throw new InvalidOperationException();  
  3. }  
  4. return value;  
Now let’s have a look at how we populate our input parameter into textSpan. The input parameter is an instance of a buffer that can read a sequential series of bytes.
ReadableBuffer is inherited from ISequence<ReadOnlyMemory<byte>> which basically means that it consists of multiple memory segments.
In case buffer consists of a single segment we just use the underlying Span from the first segment.
  1. if (buffer.IsSingleSpan) {  
  2.     textSpan = buffer.First.Span;  
  3. }  
Otherwise, we allocate data on the stack and create a Span<byte> based on it.
  1. var data = stackalloc byte[128];  
  2. var destination = new Span<byte>(data, 128);  
Then we use method buffer.CopyTo(destination) which iterates over each memory segment of a buffer and copies it to a destination Span. After that we just slice a Span of buffer’s length.
  1. textSpan = destination.Slice(0, buffer.Length);  
This example shows us that the new Span<T> API allows us to work with memory manually allocated on a stack in a much more convenient fashion than prior to its arrival.


Span<T> provides a safe and easy-to-use alternative to stackalloc which allows easy to get performance improvement. While the gain from each usage of it is relatively small the consistent usage of it allows us to avoid what is known as a death by thousand cuts. Span<T> is widely used across .NET Core 3.0 codebase which allowed us to get a perfomance improvement comparing to the previous version.
Here are some things you might consider when you decide whether you should use Span<T>,
  • If your method accepts an array of data and doesn’t change its size. If you don’t modify an input you might consider ReadOnlySpan<T>.
  • If your method accepts a string to count some statistics or to perform a syntactical analysis you should accept ReadOnlySpan<char>.
  • If your method returns a short array of data you can return Span<T> with the help of Span<T> buf = stackalloc T[size]. Remember that T should be a value type.

Recommended Free Ebook
Similar Articles