Developer knowledge network ยท moderated exchange

Onbetrouwbare Code-gemeenschap

Ontwikkelaarsonderzoek, reverse engineering en coderingsgemeenschap

Knowledge indexLive
4Categories
919Threads
2.8KBerichten
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
Vertegenwoordiger: 103
Datum van deelname: Apr 2018
Berichten: 40
Bedankt: 24
1 maanden geleden ยท 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
Vertegenwoordiger: 146
Datum van deelname: Aug 2019
Berichten: 33
Bedankt: 31
1 maanden geleden ยท 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
Vertegenwoordiger: 160
Datum van deelname: Jul 2022
Berichten: 10
Bedankt: 38
1 maanden geleden ยท 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.