Roadmap › C# Language — Basics to Advanced › Module: Errors, Resources and Memory
Lessons in this course (38)

30. Span<T>, Memory<T> and performance basics

AdvancedMediumLesson 30 of 38

Span<T> is a ref struct view over contiguous memory (array, stack, native) with no allocation.

csharp
ReadOnlySpan<char> line = "2026-10-20,Pune,42";
int comma = line.IndexOf(',');
ReadOnlySpan<char> date = line[..comma];       // slice — no new string
int value = int.Parse(line[(line.LastIndexOf(',') + 1)..]);

Span<byte> buffer = stackalloc byte[256];      // stack memory, no GC
  • Span<T> cannot be stored on the heap (no fields in classes, no boxing). Use Memory<T> when you need to keep it or use it across await.
  • Other tools: ArrayPool<T>.Shared, StringBuilder pooling, avoiding LINQ in hot loops, struct enumerators.