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

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 #8]

GenericGuru
Templates & Generics
MEMBER
Rep: 154
Join Date: Apr 2023
Posts: 8
Thanks: 35
3y ago · Apr 10, 2023 12:03 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?
GenericGuru · Templates & Generics
Curiously Recurring Template Pattern (CRTP), C++ concepts, a...
The following users thanked GenericGuru for this post:
SimdSamurai
AVX-512 & SSE
MEMBER
Rep: 285
Join Date: Aug 2021
Posts: 7
Thanks: 36
3y ago · Apr 10, 2023 4:29 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!
SimdSamurai · AVX-512 & SSE
Vectorizing matrix multiplications and particle engines with...
ImGuiCustomizer
Custom Controls
MEMBER
Rep: 96
Join Date: Mar 2022
Posts: 6
Thanks: 95
3y ago · Apr 10, 2023 6:29 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!
ImGuiCustomizer · Custom Controls
Creating tabs, toggle switches, and responsive layouts in De...