C# Mastery

High-Performance Memory: Span<T> and ReadOnlySpan<T>

1 Views Updated 5/4/2026

Span and High-Performance Memory

In traditional C#, slicing a string or an array created a brand new copy of that data in memory. For high-performance parsers (like JSON or CSV readers), this literally wasted Gigabytes of RAM. Span<T> allows us to point to a "Window" of existing memory without copying a single byte.

1. What is a Span?

A Span<T> is a **ref struct**—a type-safe, stack-only pointer. It can point to an Array, an unmanaged memory block, or even data on the Stack.

string bigContent = "ID:54321;STATUS:ACTIVE";

// ❌ OLD WAY: Creates a new string "54321" on the heap
string id = bigContent.Substring(3, 5); 

// ✅ MODERN WAY: 'idSpan' is just a pointer to the middle of the original string!
// ZERO memory allocation.
ReadOnlySpan<char> idSpan = bigContent.AsSpan(3, 5);

2. Ref Struct Constraints

Because Spans are stack-only for performance, they have strict rules. You cannot use them inside an async method, you cannot store them as fields in a class, and they cannot be used in a List<Span>.

3. Memory<T>: The Async Alternative

If you need "Span-like" behavior but you are working in an async method, you use Memory<T>. It is a heap-based wrapper that can eventually be converted into a Span when it hits a synchronous method.

4. Interview Mastery

Q: "How did Span allow Microsoft to make .NET 8 several hundred percent faster than legacy .NET Framework?"

Architect Answer: "Before Span, the entire .NET runtime was addicted to 'Substrings.' Every time the framework parsed an HTTP header or a JSON key, it created thousands of tiny string objects. This caused massive Garbage Collector (GC) pressure. By rewriting the core libraries (JSON, HTTP, Regex) to use `ReadOnlySpan` and `ReadOnlySpan`, they eliminated millions of heap allocations per second. The CPU spent less time cleaning up garbage and more time executing business logic, leading to .NET consistently topping the TechEmpower performance benchmarks."

C# Mastery
1. Modern C# & Framework Fundamentals
Introduction to the .NET Ecosystem & Runtime (JIT, CLR) C# 12/13 Top-Level Statements & Global Usings Variables, Data Types, and Value vs Reference Deep Dive Mastering Nullable Reference Types & Null Safety The Magic of Strings (Interpolation, Verbatim, and Immutability)
2. Control Flow & Logical Structures
Advanced Pattern Matching (Switch Expressions) The Precision of Numbers: Checked vs Unchecked Math Iterators: Foreach, Yield Return, and Deferred Execution Defensive Programming: Guard Clauses and Exception Mastery
3. Object-Oriented Mastery
Classes vs Structs vs Records (Which to use when?) Mastering Primary Constructors & Object Initializers Interface Architectures: Default Implementations & Segregation Polymorphism vs Composition (The Architect's Dilemma) Partial Classes, Extension Methods, and Static Classes
4. Functional C# & Collections
Delegates, Func, Action, and Predicates Lambda Expressions & The Evolution of Linq Dynamic Array Management: List<T>, Dictionary, and HashSet Custom Collections & Yielding Data streams
5. Asynchronous & Parallel Programming
Async/Await Deep Dive: Task Lifecycle & Thread Safety Synchronization Context & Avoiding Deadlocks Parallel.ForEach vs PLINQ vs Tasks CancellationToken Mastery: Surgically Aborting Operations
6. Advanced Engineering & High Performance
Generics & Constraints: Building Type-Safe Libraries Reflection and Attributes: Reading Metadata at Runtime Dependency Injection Internals (ServiceCollection from scratch) High-Performance Memory: Span<T> and ReadOnlySpan<T> Garbage Collection Segments & LOH Internals Managing Unmanaged Resources: IDisposable & Finalizers Introduction to Source Generators & Interceptors C# Interview Masterclass: Architect-Level Explanations