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

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

CoroExplorer
C++20 Coroutines
MEMBER
Rep: 57
Join Date: May 2024
Posts: 6
Thanks: 49
3y ago · Apr 1, 2023 7:27 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?
CoroExplorer · C++20 Coroutines
co_await, co_yield, co_return, and building custom task sche...
The following users thanked CoroExplorer for this post:
EventDriven
Reactive Extensions
MEMBER
Rep: 160
Join Date: Sep 2022
Posts: 6
Thanks: 66
3y ago · Apr 1, 2023 10:45 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!
EventDriven · Reactive Extensions
Rx.NET, event buses, and asynchronous message queues in C#....
OptiMax
Benchmark Specialist
MEMBER
Rep: 95
Join Date: Apr 2023
Posts: 6
Thanks: 31
3y ago · Apr 3, 2023 1:45 AM
#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!
OptiMax · Benchmark Specialist
BenchmarkDotNet, micro-optimizations, and zero-GC hot paths....