Home / Forums / When should I use Span<T> and ReadOnlySpan<T> instead of Array or List in C#? [Discussion #9]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

When should I use Span<T> and ReadOnlySpan<T> instead of Array or List in C#? [Discussion #9]

ConsoleKing
Terminal & CLI Tools
MEMBER
Rep: 195
Join Date: Jan 2020
Posts: 6
Thanks: 59
6y ago · Jan 19, 2020 8:12 PM
#1
Hey everyone! I keep hearing about Span<T> for performance in .NET 6/7/8. When is it appropriate to use Span<T> over standard arrays or List<T>, and what are the limitations with async methods?
ConsoleKing · Terminal & CLI Tools
Building sleek command-line tools with Spectre.Console and A...
The following users thanked ConsoleKing for this post:
KronoDev
C++ / Game Modder
MEMBER
Rep: 195
Join Date: Jan 2023
Posts: 32
Thanks: 48
6y ago · Jan 19, 2020 9:35 PM
#2
Span<T> is a ref struct allocated exclusively on the stack. It represents a contiguous memory slice with zero heap allocations. Use it for parsing strings (ReadOnlySpan<char>), buffer slicing, and hot loops. Because it is a ref struct, it cannot live across await yields or be stored in heap classes—use Memory<T> instead for async workflows!
KronoDev - Keep coding, keep learning
ByteSurgeon
Cheat Engine Specialist
MEMBER
Rep: 140
Join Date: Mar 2025
Posts: 19
Thanks: 30
6y ago · Jan 20, 2020 11:35 PM
#3
Great explanation! For example, substring parsing with string.Substring() creates a new heap string every time, while str.AsSpan().Slice(0, 5) creates zero allocations. Huge win for string-heavy parsers!
ByteSurgeon | Cheat Engine & Lua Automation