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

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#?

HexRays99
Senior Reverse Engineer
VIP
Rep: 380
Join Date: Apr 2022
Posts: 36
Thanks: 94
6y ago · Jan 1, 2020 8:00 AM
#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?
HexRays99 · Reverse Engineering & Static Analysis
CPP
// Always check your pointers!
if (!pLocalPlayer) return;
The following users thanked HexRays99 for this post:
RenderMaster
ImGui UI Designer
VIP
Rep: 310
Join Date: Sep 2023
Posts: 32
Thanks: 82
6y ago · Jan 1, 2020 12:10 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!
RenderMaster | Clean UI Design & Dear ImGui widgets
RustMechanic
Unity & IL2CPP Reverser
VIP
Rep: 295
Join Date: Nov 2022
Posts: 32
Thanks: 74
6y ago · Jan 1, 2020 5:10 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!
RustMechanic | IL2CPP & Unity Engine Analysis