C# & CLR Internals (50 Qs)•Part 1: Core Language, CLR & Memory Architecture (1 - 10)
What are `Span<T>`, `ReadOnlySpan<T>`, and `Memory<T>`, and why are they critical for high performance?
senior LevelCode ExampleFormsPerformanceSystem Design
In Simple Words:
Span<T>: Aref structthat represents a contiguous region of arbitrary memory (managed heap array, unmanaged native heap, or stack-allocated memorystackalloc) without allocating new heap memory or copying bytes.- It enables zero-allocation string slicing, parsing, and buffer manipulation.
- Because
Span<T>is aref struct, it can ONLY live on the stack (cannot be boxed or captured in async methods). Memory<T>: A heap-safe wrapper over contiguous memory that CAN survive acrossasync/awaitstate boundaries.
csharp
// Zero-Allocation String Slicing with ReadOnlySpan:
string header = "Content-Length: 4096";
ReadOnlySpan<char> span = header.AsSpan();
// Slice without creating a new string on the heap:
int colonIndex = span.IndexOf(':');
ReadOnlySpan<char> valueSpan = span.Slice(colonIndex + 1).Trim();
int length = int.Parse(valueSpan); // Parsed directly from span