Practical allocation reduction on a hot path with Span<T>, ArrayPool<T>, string.Create and removing LINQ and closure allocations, measured with BenchmarkDotNet's MemoryDiagnoser.
First I prove the method is hot: dotnet-counters shows a high allocation rate and an allocation profile points at it. Then I write a BenchmarkDotNet benchmark with [MemoryDiagnoser] so every change shows Mean and Allocated bytes.
The usual fixes:
ReadOnlySpan<char> slicing instead of Substring and Split, which allocate a string per piece.string.Create (or stackalloc plus TryFormat) to build the final string once.ArrayPool<T>.Shared for temporary buffers, returned in finally.The trade-off is readability: span-based code is harder to maintain, so I only do it where the profile and the benchmark justify it.
"I only do this after a profile tells me a method is hot. Typically
dotnet-countersshows an allocation rate of hundreds of megabytes a second, time in GC is high, and an allocation trace in Visual Studio or PerfView points at one method, often a parser or a formatter called for every request or message.I then write a BenchmarkDotNet benchmark with
[MemoryDiagnoser]and the current code as the baseline. Allocations on hot paths usually come from four places:SubstringandSplitcreating a string per token, string concatenation or interpolation creating intermediates, temporary arrays and lists, and LINQ or lambdas that capture variables, which allocate an enumerator, a closure object and a delegate. The fixes are parsing withReadOnlySpan<char>andint.Parse(ReadOnlySpan<char>), building output withstring.Createor a stack buffer andTryFormat, renting temporary arrays fromArrayPool<T>.Sharedand returning them in afinally, and replacing LINQ in the inner loop with aforeachor a span loop.The mistake I see is applying these everywhere. A
Splitin a controller that runs once per request is fine; the sameSplitin a loop over a million rows isn't. I keep the optimised version small, covered by tests that compare it with the simple version, and I verify the win in production by watching allocation rate and p99, not just the benchmark."
| Source | Allocates | Replacement |
|---|---|---|
line.Split(',') |
string[] plus one string per field |
ReadOnlySpan<char> + IndexOf, or MemoryExtensions.Split into Span<Range> |
s.Substring(a, b) |
New string | s.AsSpan(a, b) |
a + "-" + b in a loop |
Intermediate strings | string.Create, StringBuilder, interpolated handler into a span |
new byte[4096] per call |
Array (LOH if > 85 KB) | ArrayPool<byte>.Shared.Rent / stackalloc for small sizes |
items.Where(x => x.Id == id) |
Closure, delegate, enumerator | foreach with a local comparison |
value.ToString() then append |
String | value.TryFormat(span, out var written) |
Boxing (object, non-generic interfaces) |
Box per value | Generics, IEquatable<T> |
| Method | Mean | Allocated |
|---|---|---|
| ParseWithSplit (baseline) | 412 ns | 616 B |
| ParseWithSpan | 96 ns | 0 B |
| FormatWithConcat (baseline) | 188 ns | 216 B |
| FormatWithStringCreate | 61 ns | 64 B |
(Illustrative numbers from a typical laptop; always run on your own hardware.)
A message consumer parsed 40,000 CSV lines a second with Split and LINQ, allocating about 700 MB/s with 15% time in GC. A span-based parser plus a pooled output buffer dropped allocations to 35 MB/s, time in GC to under 2%, and let the same pod count handle 2.5 times the throughput.
Checks whether the candidate can reduce allocations with modern APIs and prove the gain, without over-applying the techniques.
Green flags
Red flags
Allocation itself is cheap: a pointer bump in the thread's allocation context. The cost comes later. Every ~few MB of Gen 0 allocation triggers a GC; survivors are copied to Gen 1 and Gen 2; Gen 2 and LOH collections are expensive and cause latency spikes. Fewer allocations mean fewer GCs and a lower p99.
alloc-rate --> Gen0 GC frequency --> promotions --> Gen2 GCs --> p99 spikes
Span<T> and ReadOnlySpan<T> are ref structs that describe a window over existing memory (array, string, stack, native). Slicing a span is just a new (pointer, length) pair: no copy, no allocation. Because they're stack-only they can't be stored on the heap or cross an await; use Memory<T> there. Most BCL parsing and formatting APIs have span overloads: int.Parse(ReadOnlySpan<char>), TryFormat, Utf8Formatter, Encoding.GetBytes(ReadOnlySpan<char>, Span<byte>).
string.Create(length, state, (span, state) => ...) allocates the final string once and gives you its buffer as a Span<char> to fill. Pass state explicitly (often a tuple) so the lambda is static and allocates no closure.
ArrayPool<T>.Shared keeps per-core buckets of arrays by power-of-two size. Rent(n) may return a larger array; always use the length you asked for. Return in a finally; never use the array after returning it; pass clearArray: true if it held sensitive data. For small, fixed sizes, stackalloc into a Span<T> is cheaper (keep it under ~1 KB and never in a loop).
A lambda that captures a local compiles to a display class allocated on each call, plus a delegate. LINQ over IEnumerable<T> allocates an enumerator per operator. .NET 9 and 10 made LINQ much faster for arrays and lists, but in a tight loop a foreach still allocates nothing. Use static lambdas to make the compiler stop you capturing by accident.
BenchmarkDotNet runs warm-up, pilot and measurement phases, forces Release builds and reports statistics. [MemoryDiagnoser] adds Gen0 collections and Allocated per operation. Return results from benchmarks so the JIT can't remove the work as dead code.
[Params(10, 1000)] for the number of fields and see where the span version's lead grows.static and fix the compile errors it reveals.dotnet-counters on a sample API before and after replacing Split in a hot loop, and record alloc-rate.Return in a test and see the corruption it can cause.Before and after for a hot CSV-style parser and formatter, with the BenchmarkDotNet harness that proves the change.
// LineParser.cs
using System.Buffers;
using System.Text;
namespace Perf.Parsing;
public readonly record struct Reading(int SensorId, int Value);
public static class LineParser
{
// Before: Split allocates a string[] plus a string per field.
public static Reading ParseWithSplit(string line)
{
var parts = line.Split(',');
return new Reading(int.Parse(parts[0]), int.Parse(parts[1]));
}
// After: slice the span; int.Parse has a ReadOnlySpan<char> overload. Zero allocations.
public static Reading ParseWithSpan(string line)
{
ReadOnlySpan<char> span = line;
var comma = span.IndexOf(',');
return new Reading(int.Parse(span[..comma]), int.Parse(span[(comma + 1)..]));
}
// Before: two ToString() intermediates, then a concatenated result string.
public static string FormatWithConcat(Reading r) => r.SensorId.ToString() + ":" + r.Value.ToString();
// After: format into a small stack buffer, then allocate only the final string.
public static string FormatWithStackBuffer(Reading r)
{
Span<char> buffer = stackalloc char[23]; // two ints (max 11 chars each) + ':'
r.SensorId.TryFormat(buffer, out var written);
buffer[written++] = ':';
r.Value.TryFormat(buffer[written..], out var second);
return new string(buffer[..(written + second)]);
}
// Temporary buffer from the pool, always returned in finally.
public static int ChecksumUtf8(string text)
{
var max = Encoding.UTF8.GetMaxByteCount(text.Length);
var buffer = ArrayPool<byte>.Shared.Rent(max);
try
{
var count = Encoding.UTF8.GetBytes(text, buffer);
var sum = 0;
foreach (var b in buffer.AsSpan(0, count)) sum += b; // only the bytes we wrote
return sum;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
// ParserBenchmarks.cs: dotnet run -c Release
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Perf.Parsing;
BenchmarkRunner.Run<ParserBenchmarks>();
[MemoryDiagnoser]
public class ParserBenchmarks
{
private const string Line = "48213,1772";
private static readonly Reading Sample = new(48213, 1772);
[Benchmark(Baseline = true)] public Reading Split() => LineParser.ParseWithSplit(Line);
[Benchmark] public Reading Span() => LineParser.ParseWithSpan(Line);
[Benchmark] public string Concat() => LineParser.FormatWithConcat(Sample);
[Benchmark] public string StackBuffer() => LineParser.FormatWithStackBuffer(Sample);
}
For variable-length output where you can compute the length up front, string.Create(length, state, static (span, s) => ...) goes one step further and writes directly into the final string's buffer.
Rent(100) can return 128 elements with stale data. Instead: Track the requested length and slice.Return. Why it is wrong: Another caller may already own it, leading to corrupted or leaked data. Instead: Return once, in finally, and drop the reference.stackalloc with a size from user input or inside a loop. Why it is wrong: A stack overflow kills the process. Instead: Use a small constant threshold and fall back to ArrayPool.Allocation reduction is a targeted tool: on a typical line-of-business API, the database dominates and this work moves nothing. It pays off in high-throughput parsers, serialisers, middleware, logging and message consumers. Prefer framework features first: System.Text.Json source generation, SearchValues<T>, CollectionsMarshal, and the span overloads the BCL already has. Keep the simple version in tests as an oracle for the optimised one.
| Technique | When it fits | Cost | When not to |
|---|---|---|---|
| Span slicing | Parsing strings and bytes in hot loops | Can't cross await or live on the heap | Code that needs to store pieces |
| string.Create | Building many small strings of known length | More complex code | One-off messages |
| ArrayPool | Temporary buffers > ~1 KB | Rent/return discipline; misuse leaks data | Buffers that escape the method |
| Remove LINQ | Inner loops over large collections | Less declarative code | Request-level queries over small lists |
Span<T> is a ref struct holding a reference and a length: a typed, bounds-checked view over contiguous memory, whether that memory is an array, a stackalloc buffer, native memory or part of a string (through ReadOnlySpan<char>). Slicing (span[2..6], Slice) creates a new view without copying, so parsers and formatters can work on pieces of a buffer with no allocations. Because it can point at the stack, it is stack-only: it cannot be a field of a class, be boxed, be captured by a lambda, or live across await/yield (C# 13 allows span locals in async and iterator methods as long as they do not cross those points). Helpers in MemoryExtensions (IndexOf, SequenceEqual, Sort, Trim) are vectorised. CollectionsMarshal.AsSpan(list) exposes a list's backing array, but adding to the list invalidates it.
Pooling bugs are lifetime bugs: the pool gives a returned array to the next renter, so any code still using it reads or writes someone else's data. The usual causes are use after return (returning in finally while an async continuation, a queued Memory<T> or a lazy enumerable still uses the array), double return (two renters then share one array), treating array.Length as the data length (Rent returns an array at least as large as requested, with old contents), not clearing buffers that held secrets (Return(array, clearArray: true)), and returning arrays not rented from that pool. To debug: reproduce under concurrency, add canaries or a poisoning wrapper pool in tests that fills returned arrays with a marker and detects double returns, trace System.Buffers.ArrayPoolEventSource events, and review every rent for a single owner and a single return in finally.
Boxing wraps a value type in a new heap object so it can be used as object or an interface; unboxing checks the object's type and copies the value back, and it must be the exact type or you get InvalidCastException. Every box is a heap allocation, so in hot paths it creates GC pressure. Hidden boxing comes from non-generic APIs like ArrayList and params object[], passing structs as interfaces, calling GetType() or non-overridden Equals/GetHashCode on structs, and enumerating a List<T> through IEnumerable<T>. I find it with BenchmarkDotNet's MemoryDiagnoser or an allocation profiler and fix it with generics, constraints and IEquatable<T>.
How to tell it (STAR)
**S:** At [company] our ingestion worker needed [12] pods to keep up and spent about [15%] of its time in garbage collection. **T:** I was asked to cut the cost without a rewrite. **A:** I measured first: dotnet-counters showed [700 MB/s] of allocations, and a PerfView allocation trace pinned most of it on Split and LINQ in the parser. I wrote a BenchmarkDotNet baseline, rebuilt the parser with spans and pooled buffers, kept the old parser as a test oracle, and shipped behind a flag. **R:** Allocations fell to [35 MB/s], time in GC under [2%], and we handled the same load with [5] pods, saving about [$X] a month.
Last updated 23 Nov 2026.