C# & CLR Internals (50 Qs)•Part 3: CLR Internals, Native AOT & Production Diagnostics (25 - 35)
Zero-Allocation Memory Slicing: `Span<T>` and `ReadOnlySpan<T>`.
senior LevelCode ExamplecsharpCLR Internals
In Simple Words:
Prior to Span<T>, string manipulation (substring, split) allocated millions of short-lived strings on the heap, triggering heavy GC pauses.
Span<T>/ReadOnlySpan<T>: A stack-onlyref structrepresenting a contiguous region of arbitrary memory (managed array, native memory, or stackallocated buffer).- Zero-Allocation Slicing: Slicing a span (
span.Slice(0, 5)) creates an offset view pointing directly into existing memory with zero heap allocations!
csharp
ReadOnlySpan<char> text = "ORDER-2026-11-20".AsSpan();
// Slices text with 0 heap allocation and 0 bytes garbage generated!
ReadOnlySpan<char> yearSpan = text.Slice(6, 4);
int year = int.Parse(yearSpan);