Every object you allocate is work the garbage collector does later. In a busy web app, allocations in hot paths (parsing headers, building strings, hashing) add up to collections that pause your requests. Span<T>, stackalloc and ArrayPool<T> let you do the same work with far less garbage. This post shows each on everyday tasks, with the rules that keep them safe.
What a span is
A Span<T> is a view over memory you already have: part of an array, part of a string, or a buffer on the stack. Slicing a span creates no copy and no new object.
string line = "2026-11-29,order-1042,149.90";
// Substring: allocates three new strings.
var parts = line.Split(',');
// Span: no allocations, just views into the original string.
ReadOnlySpan<char> span = line;
var date = span[..10];
var amount = span[(span.LastIndexOf(',') + 1)..];ReadOnlySpan<char> is how you look at text without copying it. Most parsing APIs accept it:
var total = decimal.Parse(amount, CultureInfo.InvariantCulture);
var day = DateOnly.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture);Splitting without allocating
MemoryExtensions.Split on a span enumerates ranges instead of creating strings:
ReadOnlySpan<char> csv = "aspnet-core,csharp,ef-core";
foreach (var range in csv.Split(','))
{
ReadOnlySpan<char> tag = csv[range];
if (tag.Equals("csharp", StringComparison.Ordinal))
{
// found it, no strings created
}
}stackalloc for small, short-lived buffers
For small buffers that only live inside one method, stackalloc puts them on the stack. The memory disappears when the method returns, so the garbage collector never sees it.
static string ToHex(ReadOnlySpan<byte> hash)
{
Span<char> chars = stackalloc char[hash.Length * 2];
for (var i = 0; i < hash.Length; i++)
{
var b = hash[i];
chars[i * 2] = "0123456789abcdef"[b >> 4];
chars[i * 2 + 1] = "0123456789abcdef"[b & 0xF];
}
return new string(chars); // the only allocation: the result
}(Convert.ToHexString does this for you; the example shows the technique.)
Keep stackalloc small, a few hundred bytes to about 1 KB, and never size it from user input. The stack is about 1 MB per thread; a large or attacker-controlled size can crash the process with a stack overflow.
ArrayPool for bigger or variable buffers
When the size is large or unknown, rent a buffer from the shared pool and give it back:
static async Task<int> CountLinesAsync(Stream stream, CancellationToken ct)
{
var buffer = ArrayPool<byte>.Shared.Rent(64 * 1024);
try
{
var lines = 0;
int read;
while ((read = await stream.ReadAsync(buffer.AsMemory(0, 64 * 1024), ct)) > 0)
{
lines += buffer.AsSpan(0, read).Count((byte)'\n');
}
return lines;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}Three rules for pooled arrays:
- The array may be bigger than you asked for. Always use the length you requested, not
buffer.Length. - Always return it, in a
finallyblock. - Never use it after returning it. Another caller may already have it.
The common pattern: stack when small, pool when big
static string Normalise(ReadOnlySpan<char> input)
{
const int StackLimit = 256;
char[]? rented = null;
Span<char> buffer = input.Length <= StackLimit
? stackalloc char[StackLimit]
: (rented = ArrayPool<char>.Shared.Rent(input.Length));
try
{
var written = 0;
foreach (var c in input)
{
if (char.IsLetterOrDigit(c)) buffer[written++] = char.ToLowerInvariant(c);
}
return new string(buffer[..written]);
}
finally
{
if (rented is not null) ArrayPool<char>.Shared.Return(rented);
}
}This is the pattern the .NET libraries use internally: no heap allocation for typical input, and still correct for large input.
Building strings
string.Create writes directly into the new string's memory, with no intermediate buffer:
static string OrderReference(int year, int number) =>
string.Create(12, (year, number), static (span, state) =>
{
"ORD-".CopyTo(span);
state.year.TryFormat(span[4..], out _);
span[8] = '-';
(state.number % 1000).TryFormat(span[9..], out _, "000");
});For everyday string building, interpolated strings are already efficient on modern .NET: the compiler uses DefaultInterpolatedStringHandler, which avoids boxing and intermediate strings. Reach for string.Create only when a benchmark says so.
Where spans can't go
Span<T> is a ref struct, so it lives only on the stack:
- No
Span<T>fields in classes. - No
Span<T>across anawaitinasyncmethods. - No
Span<T>captured in lambdas.
When you need a slice that survives an await, use Memory<T> / ReadOnlyMemory<T> and call .Span when you're ready to work on it.
Measure first
Spans make code longer. Use them where a profiler or BenchmarkDotNet shows allocations in a hot path: request parsing, serialization, hashing, tight loops. Elsewhere, clear code with a few small allocations is the better trade.
Wrapping up
ReadOnlySpan<char> for slicing and parsing text, stackalloc for small fixed buffers, ArrayPool<T> for large ones, and string.Create for building results. Used in the few places that matter, they remove most of the garbage your hot paths produce, and the garbage collector pauses with it.