Skip to main content
InterviewHubPRO
Section Overview
Q4

Question 4 of 50

Part 1: Core Language, CLR & Memory Architecture (1 - 10)

8%
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>: A ref struct that represents a contiguous region of arbitrary memory (managed heap array, unmanaged native heap, or stack-allocated memory stackalloc) without allocating new heap memory or copying bytes.
  • It enables zero-allocation string slicing, parsing, and buffer manipulation.
  • Because Span<T> is a ref 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 across async/await state 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