Spans and Performance: Zero-Copy Work

Spans and Performance: Zero-Copy Work in C#: You need three paragraphs out of a thousand-page reference book.

The Analogy: Bookmarks Instead of Photocopies

You need three paragraphs out of a thousand-page reference book. The obvious approach is to photocopy them: now you have your own pages, you can scribble on them, and they will still exist after the library closes. The cost is a trip to the copier for every extract, a growing pile of paper, and somebody eventually having to recycle it all.

The other approach is a pair of bookmarks. "Pages 412 to 414" is a complete description of the passage, it takes a second to produce, and it involves no paper at all. The catch is that a bookmark is only meaningful while the book is on the shelf — you cannot mail it to a colleague, you cannot keep it after the book is returned, and if somebody reshelves the volume your bookmark now points at a cookbook.

Span<T> is the pair of bookmarks. It is a start address and a length: a window onto memory that somebody else owns, whether that memory is an array, a string, a slice of another span, or a buffer carved out of the current stack frame. Slicing a span costs two integers and no allocation, and reading through it is exactly as fast as indexing the underlying array, because it is the underlying array.

That is the whole performance idea of this lesson, and it generalises past Span. Most real optimisation in C# is not clever arithmetic; it is removing work that never needed to happen — the substring that was only going to be parsed, the List that was only going to be counted, the StringBuilder that could have written straight into a buffer. Photocopies you never keep are the most common waste in a .NET application, and the tools in this lesson exist to stop making them.


Syntax or Core Structure

using System;

class Program
{
    static void Main()
    {
        string line = "2026-08-31";
        ReadOnlySpan<char> span = line.AsSpan();

        int year  = int.Parse(span.Slice(0, 4));   // no substring allocated
        int month = int.Parse(span.Slice(5, 2));
        int day   = int.Parse(span.Slice(8, 2));
        Console.WriteLine(year + " / " + month + " / " + day);

        // A slice is a window, not a copy: writes reach the original array.
        int[] numbers = { 1, 2, 3, 4, 5, 6 };
        Span<int> middle = numbers.AsSpan(2, 3);   // views 3, 4, 5
        middle[0] = 30;
        Console.WriteLine(string.Join(", ", numbers));

        middle.Sort();                             // sorts in place, allocation-free
        Console.WriteLine(string.Join(", ", numbers));

        // stackalloc: a scratch buffer with no heap involvement at all
        Span<char> buffer = stackalloc char[5];
        "abcde".AsSpan().CopyTo(buffer);
        buffer.Reverse();
        Console.WriteLine(new string(buffer));

        Console.WriteLine("length " + span.Length
            + ", trimmed " + " hi ".AsSpan().Trim().Length);
    }
}

Output:

2026 / 8 / 31
1, 2, 30, 4, 5, 6
1, 2, 4, 5, 30, 6
edcba
length 10, trimmed 2

The date parse is the everyday win. Written the traditional way — int.Parse(line.Substring(0, 4)) three times — it allocates three short-lived strings per line, which is nothing once and a great deal in a loop over a million log entries. The span version does the identical parsing work with zero allocations, and the code is no harder to read.

The two numbers lines show that a span is genuinely a window. middle[0] = 30 writes into numbers[2], and middle.Sort() reorders numbers[2..5] in place, leaving elements 0, 1 and 5 untouched — which is why the final array is 1, 2, 4, 5, 30, 6 rather than sorted overall. If you wanted a copy you would ask for one with ToArray(); the default is a view, and that default is the entire point.

stackalloc char[5] carves the buffer out of the current stack frame: no allocation, no garbage, and no possibility of it outliving Main. new string(buffer) is the one deliberate allocation in the whole example, because a string is what Console.WriteLine needs. The pattern generalises — do all the manipulation in a stack buffer and materialise a heap object only at the boundary where something else demands one.


Technical Depth: The Toolbox and Its Limits

Span<T> is a ref struct holding a managed reference plus a length. That single design choice explains all of its restrictions:

You cannotBecause
Store a Span in a class fieldThe field could outlive the stack frame it points at
Use one across await or yieldThe continuation may resume on a different stack
Capture one in a lambdaThe closure is a heap object
Box one, or put it in List<Span<T>>Both require heap storage
Use one as a generic type argumentSame reason, until allows ref struct in C# 13

Memory<T> is the answer to those cases: it is a normal struct that can live in a field and cross an await, and you call .Span to get the fast window when you actually need to read or write.

TypeLives whereUse for
T[]Heap, owns its dataLong-term storage
Span<T> / ReadOnlySpan<T>Stack only, borrowsSynchronous slicing and parsing
Memory<T> / ReadOnlyMemory<T>Anywhere, borrowsAsync APIs, fields, buffers passed around
ArraySegment<T>Anywhere, borrows an arrayLegacy APIs predating Memory

Allocation-free equivalents worth memorising

Instead ofUse
s.Substring(a, b) for parsings.AsSpan(a, b)
s.Split(',') in a loopIndexOf(',') plus Slice
s.StartsWith("x")s.AsSpan().StartsWith("x")
value.ToString() into a buffervalue.TryFormat(span, out int written)
new byte[bigSize] per callArrayPool<byte>.Shared.Rent / Return
string.Concat in a loopStringBuilder, or string.Create
list.Any()list.Count > 0
IndexOfAny(manyChars)SearchValues<char> (.NET 8+)

Renting instead of allocating

byte[] buffer = ArrayPool<byte>.Shared.Rent(minimumLength: 8192);
try
{
    Span<byte> used = buffer.AsSpan(0, 8192);   // Rent may return a LARGER array
    // ... work ...
}
finally
{
    ArrayPool<byte>.Shared.Return(buffer);      // never touch it after this
}

Two rules make pooling safe: always slice to the length you asked for, because Rent is allowed to hand back a bigger array, and always Return in a finally — while never reading the buffer afterwards, since another caller may already be using it.

Measure, then optimise

The order matters more than any individual trick. Profile first, because the bottleneck is almost never where it feels like it is; then change one thing; then measure again. Stopwatch in a loop is enough to spot a 10x difference, but tiered compilation, dead-code elimination and CPU cache effects make it unreliable below that — BenchmarkDotNet handles warm-up, multiple iterations and allocation counts, and its [MemoryDiagnoser] output is often more informative than the timings.

The traps to expect in your own measurements: benchmarking a Debug build, forgetting that the first iterations run unoptimised code, timing a loop the JIT deleted because nothing consumed the result, and drawing conclusions from a single run on a laptop with a thermal limit.

When micro-optimisation is the wrong answer

An allocation costs nanoseconds; a database round trip costs milliseconds. Shaving spans off a request that spends 40 ms waiting on SQL changes nothing measurable, and the same effort spent on an index, a cache, or one fewer query is worth thousands of times more. Reach for this toolbox on genuinely hot paths — serializers, parsers, tight numeric loops, per-request middleware — and leave the readable version everywhere else.


Real World Example: Parsing a Log Without Allocating

A log aggregator reads millions of comma-separated lines and only ever needs numbers and comparisons out of them. Every Split and every Substring on that path is a photocopy nobody keeps.

using System;

class Program
{
    static readonly string[] Lines =
    {
        "2026-08-31,INFO ,120",
        "2026-08-31,WARN ,340",
        "2026-08-31,INFO ,80",
        "2026-08-31,ERROR,1500",
        "2026-08-31,INFO ,200"
    };

    // Returns the next comma-separated field and advances the cursor.
    static ReadOnlySpan<char> NextField(ref ReadOnlySpan<char> rest)
    {
        int comma = rest.IndexOf(',');
        if (comma < 0)
        {
            ReadOnlySpan<char> last = rest;
            rest = default;
            return last;
        }

        ReadOnlySpan<char> field = rest.Slice(0, comma);
        rest = rest.Slice(comma + 1);
        return field;
    }

    static void Main()
    {
        int info = 0, warn = 0, error = 0;
        long totalMs = 0;
        int slowest = 0, slowestIndex = -1;

        for (int i = 0; i < Lines.Length; i++)
        {
            ReadOnlySpan<char> rest = Lines[i].AsSpan();
            NextField(ref rest);                                   // skip the date
            ReadOnlySpan<char> level = NextField(ref rest).Trim();
            int ms = int.Parse(NextField(ref rest));

            totalMs += ms;

            if (level.SequenceEqual("INFO")) info++;
            else if (level.SequenceEqual("WARN")) warn++;
            else if (level.SequenceEqual("ERROR")) error++;

            if (ms > slowest) { slowest = ms; slowestIndex = i; }
        }

        ReadOnlySpan<char> worst = Lines[slowestIndex].AsSpan();
        NextField(ref worst);
        ReadOnlySpan<char> worstLevel = NextField(ref worst).Trim();

        Console.WriteLine("levels (I/W/E):     " + info + "/" + warn + "/" + error);
        Console.WriteLine("total ms:           " + totalMs);
        Console.WriteLine("average ms:         " + totalMs / Lines.Length);
        Console.WriteLine("slowest:            " + slowest + "ms (" + worstLevel.ToString() + ")");
        Console.WriteLine("substrings avoided: " + Lines.Length * 3);
    }
}

Output:

levels (I/W/E):     3/1/1
total ms:           2240
average ms:         448
slowest:            1500ms (ERROR)
substrings avoided: 15

The whole loop allocates nothing. NextField takes the cursor by ref and reassigns it to a shorter window, so tokenising a line is a search for a comma and two integer updates — the same work Split does, minus the array and the three strings it would return. int.Parse accepts the span directly, Trim returns a narrower window rather than a trimmed copy, and SequenceEqual compares characters in place. Only the very last line materialises a string, and only because it is being printed.

The slowestIndex detail is a real constraint, not a stylistic choice. The obvious code would keep the winning level span in a variable across iterations — and that span points into Lines[i], which is still alive, so it would even work here. But the moment the source is a rented buffer or a stackalloc, a span held past its owner's lifetime is reading memory that now belongs to someone else. Remembering the index and re-slicing at the end is the habit that keeps the code correct when the input stops being a string literal.

There is one honest caveat: SequenceEqual is an ordinal comparison, which is exactly right for a machine-written token like INFO and exactly wrong for anything a human typed in an unknown culture. Span-based string work is fast partly because it skips culture-aware collation, so use it for protocol and format parsing and use string.Compare with an explicit StringComparison when the text is prose.

Scaled to a real log — a million lines, three fields each — the traditional version allocates three million short-lived strings plus a million arrays, all of which the collector then has to sweep. The span version allocates none of it. That is not a clever trick; it is the same parsing, with the photocopier turned off.


Common Mistakes

  1. Optimising before measuring. The hot path is rarely where intuition puts it, and a rewritten inner loop next to a slow query is wasted effort. Profile first.
  2. Storing a Span beyond its owner's lifetime. A span over a stackalloc buffer, a rented array, or a resized list becomes a window onto memory that is no longer yours. Use Memory<T> when it must be kept.
  3. Trying to use Span across await. It is a ref struct; the compiler rejects it, and Memory<T> is the async-safe equivalent.
  4. Assuming a slice is a copy. Writing through a span mutates the source array; if you need independence, call ToArray() and accept the allocation.
  5. Sizing stackalloc from input. A length that comes from a request is a stack overflow — an uncatchable process kill. Use a constant cap and fall back to ArrayPool above it.
  6. Forgetting that ArrayPool.Rent can return a longer array. Always slice to the requested length, or you will read stale data left by the previous tenant.
  7. Using a pooled buffer after returning it. Return hands ownership back; anything you read afterwards may belong to another caller.
  8. Benchmarking a Debug build or a cold run. Unoptimised code and tiered JIT make early iterations meaningless. Warm up, or use BenchmarkDotNet.

Best Practices

  • Profile, change one thing, measure again — and keep the readable version if the difference does not show up in the numbers.
  • Prefer AsSpan over Substring whenever the result is only parsed, compared, or scanned.
  • Use Memory<T> for anything stored in a field or crossing an await, and take .Span at the point of use.
  • Rent buffers of a kilobyte or more from ArrayPool<T>.Shared, slice to the requested length, and return them in a finally.
  • Keep stackalloc sizes small and constant, with an ArrayPool fallback for larger inputs.
  • Write TryFormat and TryParse overloads on your own types so callers can work in caller-supplied buffers.
  • Accept ReadOnlySpan<char> in parsing APIs so callers can pass a string, an array, or a slice without converting.
  • Keep allocation-free tricks on the paths that need them, and measure with [MemoryDiagnoser] so "fewer allocations" is a number rather than a belief.

Practice Exercises

  1. Write two versions of a CSV field counter — one with string.Split, one with IndexOf and Slice — and benchmark both over 100,000 lines, reporting elapsed time and allocated bytes for each.
  2. Implement bool TryFormatDuration(int ms, Span<char> destination, out int written) that writes strings like 1.5s or 120ms without allocating. Test it with a destination that is too small and confirm it returns false and writes nothing.
  3. Rewrite the log parser to read from a ReadOnlySpan<byte> of UTF-8 instead of string, using Utf8Parser or Encoding.UTF8. Explain which comparisons had to change and why.
  4. Take a method that builds a report with string concatenation in a loop and rewrite it three ways: StringBuilder, string.Create, and a rented char[]. Benchmark all four versions and recommend one, justifying the choice with the allocation numbers rather than the timings alone.