A short note on Span<T> and ReadOnlySpan<T>

general csharp
  • `Span<T>’s primary goal is to avoid allocating new objects on the heap when one needs to work with a contiguous region of arbitrary memory.

    • For example, arrays or strings(which are nothing but an array of chars).

  • Performance gain is two fold:-

    • The allocation on heap operation is not performed.

    • Less pressure on the GC as it does not need to track non allocated objects.

  • "111,222,333".Split(',') allocates four strings and an array to reference these 4 strings.

    • With ReadOnlySpan<char> the input string gets sliced into 4 spans.

    • uint.Parse(string) can be used to parse each sub string into integer.

  • ReadOnlySpan<T> is a structure, each span is concretely a few bytes added on the current thread stack.

  • Stack allocation is super fast and the GC is not impacted by values allocated on the stack.

  • uint.Parse(ReadOnlySpan<char>) is used to parse each slice.

  • Many dotnet apis related to string and other memory representations have been extended to accepts Span<T> or ReadOnlySpan<T>.

References