Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Discussion

Mastering Span<T> and ReadOnlySpan<T> for zero-allocation string and array parsing in C# [StackOverflow Architecture Guide]

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Өкіл: 103
Қосылу күні: Apr 2018
Хабарламалар: 40
Рахмет: 24
1 ай бұрын · Jul 23, 2026 4:43 PM
#1

How Span<T> provides contiguous memory slicing without allocating sub-arrays or substrings:

CSHARP
// Parsing date string '2026-08-22' without allocating strings for Year, Month, Day
string dateStr = "2026-08-22";
ReadOnlySpan<char> span = dateStr.AsSpan();

int year = int.Parse(span.Slice(0, 4));
int month = int.Parse(span.Slice(5, 2));
int day = int.Parse(span.Slice(8, 2));

span.Slice() is a pointer arithmetic operation on the stack ($O(1)$ time, 0 heap allocations). Unlike string.Substring() which allocates a new string on the managed heap for each segment!

profiler_pat
Performance Hunter
MEMBER
Өкіл: 146
Қосылу күні: Aug 2019
Хабарламалар: 33
Рахмет: 31
1 ай бұрын · Jul 23, 2026 9:24 PM
#2

Span<T> is defined as a ref struct, meaning it can only live on the execution stack and cannot be boxed or escape to the heap. This enables extreme memory safety.

unsafe_memory_wizard
Unsafe & P/Invoke
MEMBER
Өкіл: 160
Қосылу күні: Jul 2022
Хабарламалар: 10
Рахмет: 38
1 ай бұрын · Jul 24, 2026 2:48 PM
#3

All standard .NET BCL methods (int.Parse, Guid.Parse, Utf8Parser) now accept ReadOnlySpan<char> and ReadOnlySpan<byte> for maximum throughput.