C# Memory and Performance: Spans, Refs and Structs
This page covers the C# features for code where allocations, copies and indirection show up in a profiler: parsers, serializers, protocol handlers, numeric libraries and hot loops. They answer four questions. How do I work with part of a buffer without copying it (Span<T>, ReadOnlySpan<T> and the C# 14 span conversions)? How do I read and write data in place instead of through copies (ref locals and returns)? How do I design value types that the compiler and runtime can handle cheaply (readonly struct, ref struct)? And how do I write fast numeric code once for every number type, or drop to pointers when nothing else will do (generic math, unsafe and fixed)?
None of these features should be the default for ordinary business code. Measure first, for example with BenchmarkDotNet or dotnet-counters, and apply them where the numbers say it matters.
All samples use one invented OrdersPortal domain: order lines in CSV, SKUs, stock levels and prices. Every complete sample is a file-based program: save it as sample.cs and run dotnet run sample.cs with the .NET 10 SDK (C# 14). The output shown was produced with SDK 10.0.115.
Features on this page
Section titled “Features on this page”| Feature | Version | Use it when |
|---|---|---|
| Span and ReadOnlySpan | C# 7.2, .NET Core 2.1 | Parsing or slicing buffers and strings without allocating. |
| Implicit span conversions | C# 14 | Calling span-based APIs with arrays and strings. |
| Ref locals | C# 7.0 | Updating a struct in an array in place. |
| Ref returns | C# 7.0 | A method should hand out access to storage it owns. |
| Readonly structs | C# 7.2 | Small immutable value types such as money or coordinates. |
| Ref structs | C# 7.2 | A type must hold a span or must never reach the heap. |
| Generic math | C# 11, .NET 7 | One algorithm for int, decimal, double and more. |
| Unsafe code and fixed | C# 1 | Native interop or pointer code that spans cannot express. |
Span and ReadOnlySpan
Section titled “Span and ReadOnlySpan”Language support arrived in C# 7.2 (Visual Studio 2017 version 15.5); the types ship in .NET Core 2.1 and later, and in the System.Memory package for .NET Framework and .NET Standard 2.0. Span<T> and ReadOnlySpan<T> are views over contiguous memory: part of an array, a string, a stackalloc buffer or native memory. Slicing a span creates another view, not a copy, and indexing is bounds-checked, so you get pointer-like efficiency with memory safety.
The common pattern is to parse with spans and allocate only the values you keep. In the sample, splitting an order line with string.Split would allocate an array and four strings per line; the span version splits into a stack-allocated Range buffer and parses numbers straight from the slices, and the measured loop allocates nothing. Most .NET parsing and formatting APIs, such as int.Parse, decimal.TryParse, TryFormat and UTF-8 encoding, have span overloads.
using System.Globalization;
string csv = "SO-1001;C-100;3;24.50";
Order order = ParseOrder(csv);Console.WriteLine($"{order.Number} for {order.CustomerId}: {order.Quantity} x {order.UnitPrice}");
// Measure allocations of the parsing work itself.long before = GC.GetAllocatedBytesForCurrentThread();decimal total = 0;for (int i = 0; i < 10_000; i++) total += LineTotal(csv);long after = GC.GetAllocatedBytesForCurrentThread();Console.WriteLine($"Parsed 10,000 lines, total {total}, allocated {after - before} bytes");
static decimal LineTotal(ReadOnlySpan<char> line){ Span<Range> parts = stackalloc Range[5]; // stack buffer, no heap array int count = line.Split(parts, ';'); if (count != 4) throw new FormatException("Expected 4 fields");
int quantity = int.Parse(line[parts[2]], CultureInfo.InvariantCulture); decimal unitPrice = decimal.Parse(line[parts[3]], CultureInfo.InvariantCulture); return quantity * unitPrice;}
static Order ParseOrder(ReadOnlySpan<char> line){ Span<Range> parts = stackalloc Range[5]; line.Split(parts, ';'); return new Order( line[parts[0]].ToString(), // allocate only the strings you keep line[parts[1]].ToString(), int.Parse(line[parts[2]], CultureInfo.InvariantCulture), decimal.Parse(line[parts[3]], CultureInfo.InvariantCulture));}
public record Order(string Number, string CustomerId, int Quantity, decimal UnitPrice);Output:
SO-1001 for C-100: 3 x 24.50Parsed 10,000 lines, total 735000.00, allocated 0 bytesPitfalls:
- A span is a
ref struct: it cannot be a field of a class, be boxed, cross anawait, or be captured by a lambda. UseMemory<T>orReadOnlyMemory<T>when the view must live on the heap or across async calls. - Large or user-controlled sizes in
stackalloccan overflow the stack; keep stack buffers small and fixed, and rent fromArrayPool<T>for bigger ones.
Implicit span conversions
Section titled “Implicit span conversions”Introduced in C# 14 (.NET 10). C# 14 gives Span<T> and ReadOnlySpan<T> first-class status in the language. It adds implicit conversions from T[] to Span<T> and ReadOnlySpan<T>, from Span<T> to ReadOnlySpan<T>, from string to ReadOnlySpan<char>, and covariant conversions such as ReadOnlySpan<string> to ReadOnlySpan<object>. Crucially, these conversions now apply to extension method receivers and generic type inference, where earlier versions refused them.
The practical result is that a library can expose one extension method on ReadOnlySpan<T> and callers can use it on arrays, spans and strings alike. Compiled with LangVersion 13, the three span calls in the sample fail with CS1929 (the two extension calls) and CS1503 (the covariant argument).
int[] quantities = [3, 0, 5, 0, 2];string sku = "PEN-01";
// C# 14: an array converts implicitly to ReadOnlySpan<T>, so a span extension// method can be called directly on it. In C# 13 this line is error CS1929.Console.WriteLine($"Empty lines: {quantities.CountZeros()}");
// string -> ReadOnlySpan<char> also works for extension receivers now.Console.WriteLine($"Category: {sku.Category()}");
// Covariance: ReadOnlySpan<string> converts to ReadOnlySpan<object>.ReadOnlySpan<string> skus = ["PEN-01", "PAD-02"];PrintAll(skus);
static void PrintAll(ReadOnlySpan<object> items){ foreach (var item in items) Console.WriteLine($" {item}");}
static class SpanExtensions{ public static int CountZeros(this ReadOnlySpan<int> values) { int count = 0; foreach (int v in values) if (v == 0) count++; return count; }
public static ReadOnlySpan<char> Category(this ReadOnlySpan<char> sku) { int dash = sku.IndexOf('-'); return dash < 0 ? sku : sku[..dash]; }}Output:
Empty lines: 2Category: PEN PEN-01 PAD-02Pitfalls:
- Overload resolution now prefers span overloads.
array.Reverse()on aT[]used to call LINQ’sEnumerable.Reverse; in C# 14 it can bind to the in-placeMemoryExtensions.Reverse, which returnsvoid. .NET 10 adds an array overload toEnumerable.Reverseto keep the old meaning, but older target frameworks compiled with C# 14 can break. - Inside expression trees,
array.Contains(x)can now bind toMemoryExtensions.Contains, which the expression interpreter and some LINQ providers cannot handle. CallEnumerable.Contains(array, x)explicitly there.
Ref locals
Section titled “Ref locals”Introduced in C# 7.0 (Visual Studio 2017). A ref local, ref StockLevel slot = ref stock[1];, is an alias for an existing storage location: an array element, a field or another variable. Reads and writes through the alias go to the original, so you can update a struct inside an array without copying it out and writing it back. C# 7.2 added ref readonly locals, which give the same no-copy access but forbid writes, and C# 7.3 allowed reassigning a ref local to point somewhere else with slot = ref other;.
The difference only matters for value types. For a class, an ordinary local already holds a reference; for a struct, an ordinary local holds a copy, which is the source of the classic “I changed it but nothing happened” bug. Ref locals fix that bug and avoid copying large structs in loops.
StockLevel[] stock =[ new() { Sku = "PEN-01", OnHand = 40 }, new() { Sku = "PAD-02", OnHand = 12 },];
StockLevel copy = stock[1]; // value copy of the structcopy.OnHand -= 5;Console.WriteLine($"After copy edit: {stock[1].OnHand}");
ref StockLevel slot = ref stock[1]; // alias to the array element itselfslot.OnHand -= 5;Console.WriteLine($"After ref edit: {stock[1].OnHand}");
slot = ref stock[0]; // ref reassignment (C# 7.3)slot.OnHand += 10;Console.WriteLine($"PEN-01 now: {stock[0].OnHand}");
ref readonly StockLevel view = ref stock[0]; // read through the alias, no writes allowedConsole.WriteLine($"Read-only view: {view.Sku} {view.OnHand}");
public struct StockLevel{ public string Sku; public int OnHand;}Output:
After copy edit: 12After ref edit: 7PEN-01 now: 50Read-only view: PEN-01 50Pitfalls:
- A ref local into a
List<T>is not possible through the indexer, which returns a copy; useCollectionsMarshal.AsSpan(list)and do not add or remove items while you hold the reference. - Since C# 13, async methods and iterators may declare ref locals, but not use them across an
awaitoryield return.
Ref returns
Section titled “Ref returns”Introduced in C# 7.0 (Visual Studio 2017). A method declared ref int OnHandFor(string sku) returns a reference to storage instead of a copy of its value, using return ref expression;. The caller can store it in a ref local, write through it, or assign to the call itself: warehouse.OnHandFor("MUG-09") = 7;. Returning ref readonly hands out read access without copying.
The compiler only allows returning references that outlive the method: elements of arrays or fields of the object, never a local variable of the method itself. This is how Span<T>’s indexer, CollectionsMarshal.GetValueRefOrAddDefault and similar high-performance APIs expose data without copies.
var warehouse = new Warehouse(["PEN-01", "PAD-02", "MUG-09"]);
ref int onHand = ref warehouse.OnHandFor("PAD-02"); // ref local receives the referenceonHand += 25;warehouse.OnHandFor("MUG-09") = 7; // assign through a ref return directly
Console.WriteLine(warehouse);
try{ warehouse.OnHandFor("BAG-04");}catch (KeyNotFoundException ex){ Console.WriteLine(ex.Message);}
public class Warehouse(string[] skus){ private readonly int[] _onHand = new int[skus.Length];
// Returns a reference into _onHand, which outlives the call. public ref int OnHandFor(string sku) { int index = Array.IndexOf(skus, sku); if (index < 0) throw new KeyNotFoundException($"Unknown SKU {sku}"); return ref _onHand[index]; }
public override string ToString() => string.Join(", ", skus.Select((s, i) => $"{s}={_onHand[i]}"));}Output:
PEN-01=0, PAD-02=25, MUG-09=7Unknown SKU BAG-04Pitfalls:
- A ref return gives callers write access to private state, bypassing any validation; prefer
ref readonlyunless mutation is the point. - If the owner later replaces its storage, for example by resizing the array, references obtained earlier silently point at the old array.
Readonly structs
Section titled “Readonly structs”Introduced in C# 7.2 (Visual Studio 2017 version 15.5). Marking a struct readonly makes the compiler enforce that every instance field is readonly and every auto-property is get-only or init; assigning one in a member is an error. In return, the compiler knows no member can mutate the instance, so it can skip defensive copies when the value is accessed through an in parameter, a readonly field or a ref readonly reference.
Without readonly, calling a member on a struct in a readonly context makes the compiler copy the whole struct first, in case the member mutates it. For small value objects, such as money, measurements, identifiers and coordinates, readonly struct (or readonly record struct, C# 10) is the right default. C# 8 added readonly on individual members for structs that must stay partly mutable.
var price = new Money(24.50m, "EUR");var withTax = price.Multiply(1.2m);
Console.WriteLine($"{price} -> {withTax}");Console.WriteLine($"Rounded: {Rounded(in withTax)}");
static Money Rounded(in Money value) => // 'in' passes by reference; no defensive copy new(Math.Round(value.Amount, 1), value.Currency); // because Money is readonly
public readonly struct Money{ public Money(decimal amount, string currency) { Amount = amount; Currency = currency; }
public decimal Amount { get; } // { get; set; } here is error CS8341 public string Currency { get; }
// public void Clear() => Amount = 0; // error CS0200: property is read only
public Money Multiply(decimal factor) => new(Amount * factor, Currency); public override string ToString() => $"{Amount:0.00} {Currency}";}Output:
24.50 EUR -> 29.40 EURRounded: 29.40 EURPitfalls:
readonlyis shallow: areadonly structthat holds aList<T>or array can still have that collection changed.- Large structs (more than a few fields) are expensive to copy even when readonly; pass them with
in, or use a class.
Ref structs
Section titled “Ref structs”Introduced in C# 7.2 (Visual Studio 2017 version 15.5). A ref struct is a value type that can never be moved to the managed heap. The compiler enforces this: it cannot be boxed or converted to object, cannot be an array element, cannot be a field of a class or ordinary struct, and cannot be captured by a lambda or local function. Because of these rules a ref struct may contain Span<T> fields and, since C# 11, ref fields.
Span<T> itself is a ref struct, and custom ref structs are the tool for allocation-free readers, tokenizers and builders that hold a span over the input, like the SKU reader in the sample. C# 13 relaxed the rules: ref structs can implement interfaces (without being converted to them), can be generic arguments for type parameters marked allows ref struct, and can be used in async methods and iterators as long as they do not cross an await or yield return.
var reader = new SkuReader("PEN-01,PAD-02,,MUG-09");while (reader.TryRead(out ReadOnlySpan<char> sku)) Console.WriteLine($"SKU: {sku}");
Console.WriteLine($"Skipped empty fields: {reader.EmptyFields}");
// A ref struct can hold a span field because it can never reach the heap.public ref struct SkuReader(ReadOnlySpan<char> input){ private ReadOnlySpan<char> _remaining = input; public int EmptyFields { get; private set; }
public bool TryRead(out ReadOnlySpan<char> sku) { while (!_remaining.IsEmpty) { int comma = _remaining.IndexOf(','); ReadOnlySpan<char> field = comma < 0 ? _remaining : _remaining[..comma]; _remaining = comma < 0 ? [] : _remaining[(comma + 1)..]; if (!field.IsEmpty) { sku = field; return true; } EmptyFields++; } sku = default; return false; }}
// Not allowed, for example:// class Holder { SkuReader _reader; } // error CS8345: ref struct field in a class// object boxed = reader; // error CS0029: cannot convert (box) to objectOutput:
SKU: PEN-01SKU: PAD-02SKU: MUG-09Skipped empty fields: 1Pitfalls:
- A ref struct cannot be stored for later, which rules out caching it in a field, using it in LINQ, or returning it from an async method; design the API around a single synchronous pass.
- Returning a ref struct that wraps a
stackallocbuffer from the method that allocated it is a ref-safety error; the compiler’s escape analysis rejects it, which can be surprising until you think in lifetimes.
Generic math
Section titled “Generic math”Introduced in C# 11 (.NET 7). C# 11 allows static abstract (and static virtual) members in interfaces, and .NET 7 used that to describe arithmetic as interfaces: INumber<T>, IAdditionOperators<TSelf, TOther, TResult>, IFloatingPoint<T> and others, implemented by every built-in numeric type. A method constrained with where T : INumber<T> can use +, T.Zero, T.Max and conversions such as T.CreateChecked, and the JIT compiles a specialized version for each value type, so there is no boxing or virtual dispatch.
Generic math lets libraries write a statistics, pricing or vector routine once instead of one overload per numeric type. Application code mostly benefits indirectly, for example through LINQ’s Sum and Average and through System.Numerics.Tensors.
using System.Numerics;
int[] unitsPerDay = [12, 7, 15, 9];decimal[] revenuePerDay = [240.00m, 133.50m, 310.25m, 180.00m];double[] basketWeightsKg = [1.2, 0.8, 2.5];
Console.WriteLine($"Units: {Sum(unitsPerDay)}, avg {Average(unitsPerDay)}");Console.WriteLine($"Revenue: {Sum(revenuePerDay)}, avg {Average(revenuePerDay)}");Console.WriteLine($"Weight: {Sum(basketWeightsKg)} kg");Console.WriteLine($"Clamped discount: {Clamp(35m, 0m, 25m)}%");
// One implementation for every numeric type; no boxing, no per-type overloads.static T Sum<T>(ReadOnlySpan<T> values) where T : INumber<T>{ T total = T.Zero; // static abstract member on the interface foreach (T value in values) total += value; return total;}
static decimal Average<T>(ReadOnlySpan<T> values) where T : INumber<T> => decimal.CreateChecked(Sum(values)) / values.Length;
static T Clamp<T>(T value, T min, T max) where T : INumber<T> => T.Max(min, T.Min(value, max));Output:
Units: 43, avg 10.75Revenue: 863.75, avg 215.9375Weight: 4.5 kgClamped discount: 25%Pitfalls:
- Constrain to the narrowest interface that the algorithm needs (
IAdditionOperators,IComparisonOperators) so more types qualify;INumber<T>excludes types such asComplex. - Conversions are explicit choices:
CreateCheckedthrows on overflow,CreateSaturatingclamps andCreateTruncatingwraps. Pick deliberately when mixing types likeintanddecimal.
Unsafe code and fixed
Section titled “Unsafe code and fixed”Introduced in C# 1 (.NET Framework 1.0). Inside an unsafe context, a method, block or type marked unsafe, C# allows pointer types, the address-of operator &, pointer arithmetic and dereferencing. Because the garbage collector can move managed objects, taking a pointer to an array or string requires a fixed statement, which pins the object for the duration of the block. Compiling unsafe code requires AllowUnsafeBlocks in the project file; the sample uses the file-based directive #:property AllowUnsafeBlocks=true.
Today, spans, MemoryMarshal, Unsafe and stackalloc into a Span<T> cover most cases that once required pointers, with bounds checks and without pinning. Unsafe code remains for native interop that passes pointers, a few vectorized hot paths, and function pointers (delegate*, C# 9). C# 15 adds a memory safety preview that moves the unsafe requirement onto operations that actually dereference pointers; it requires LangVersion preview.
#:property AllowUnsafeBlocks=true
byte[] packet = [0x53, 0x4F, 0x2D, 0x31, 0x30, 0x30, 0x31]; // "SO-1001" in ASCII
Console.WriteLine($"Checksum (unsafe): {ChecksumUnsafe(packet)}");Console.WriteLine($"Checksum (span): {ChecksumSafe(packet)}");
static unsafe int ChecksumUnsafe(byte[] data){ int sum = 0; fixed (byte* start = data) // pin the array so the GC cannot move it { byte* p = start; byte* end = start + data.Length; while (p < end) sum += *p++; // pointer arithmetic, no bounds checks } // unpinned here return sum;}
static int ChecksumSafe(ReadOnlySpan<byte> data){ int sum = 0; foreach (byte b in data) sum += b; // the JIT can usually drop bounds checks here return sum;}Output:
Checksum (unsafe): 401Checksum (span): 401Pitfalls:
- Pinning many objects or pinning for a long time fragments the heap and slows the GC; keep
fixedblocks short, and useGC.AllocateArray(pinned: true)or native memory for buffers that stay pinned. - Pointer code has no bounds checks: an off-by-one reads or corrupts unrelated memory instead of throwing.
Choosing between them
Section titled “Choosing between them”- Read part of a buffer:
ReadOnlySpan<T>;Memory<T>when the view must be stored or crossawait. - Change a struct where it lives: a
reflocal, or arefreturn from the owner. Preferref readonlywhen you only need to avoid the copy. - Design a value type:
readonly structorreadonly record structby default;ref structonly when it must hold a span or must never escape to the heap. - Numeric code for many types: generic math with the smallest interface constraint that works.
- Pointers: only for interop or measured hot paths that spans cannot express, and keep the unsafe region small.
Interview questions
Section titled “Interview questions”What is the difference between Span<T> and Memory<T>?
Span<T> is a ref struct that can live only on the stack, so it is the fastest view but cannot be stored in fields, used across await, or captured. Memory<T> is an ordinary struct that can live on the heap; you call .Span on it at the point of use.
What is a defensive copy, and how do you avoid it?
When a member is called on a struct accessed through a read-only reference (an in parameter, a readonly field), the compiler cannot be sure the member does not mutate the value, so it calls the member on a copy. Declaring the struct readonly, or the member readonly, removes the uncertainty and the copy.
Why can a ref struct not be boxed or captured by a lambda?
Both would put the value on the heap, where it could outlive the stack memory a span inside it points at. The restrictions guarantee that any reference the struct holds cannot dangle.
When can a method return by ref?
When the referenced storage outlives the call: an array element, a field of a heap object, a ref parameter, or something reached through them. Returning a reference to the method’s own local is rejected by the compiler’s ref-safety analysis.
What problem does generic math solve compared with dynamic or overloads?
Overloads duplicate code per numeric type, and dynamic boxes and binds at run time. Static abstract interface members let one generic method call operators directly; the JIT specializes it per value type, so it runs as fast as hand-written overloads.
Senior scenario: profiling shows an OrdersPortal CSV import spends most of its time in the garbage collector. How do you approach it?
Confirm with allocation profiling where the bytes come from; in line-based imports it is usually string.Split, Substring and intermediate strings. Read the file with a buffered reader or System.IO.Pipelines, parse each line as a ReadOnlySpan<char> with Split into a stack Range buffer and span-based Parse, and allocate only the strings you store, possibly interning repeated values such as SKUs. Keep the parser a synchronous method or a ref struct reader, and measure before and after with BenchmarkDotNet and GC.GetAllocatedBytesForCurrentThread. Avoid unsafe unless spans leave a measured gap.
Related pages
Section titled “Related pages”- Collections and queries: index and range operators on spans, collection expressions with span targets.
- Object construction, initialization and properties: structs, records and
with. - Resource management: disposing pooled buffers and native handles.
- Async and await: why spans cannot cross
awaitand when to useMemory<T>. - Release guides: C# 7.0, C# 7.2, C# 11, C# 13, C# 14, and the version history.
Official references
Section titled “Official references”- Memory and spans overview and
Span<T>(.NET 10) - First-class span types (C# 14 specification) and C# 14 overload resolution with span parameters
- Reference variables (
reflocals and returns) - Structure types, including
readonly structandrefstructure types - Generic math
- Unsafe code, pointer types and function pointers and the
fixedstatement - What’s new in C# 15: memory safety preview