Tutorials / Advanced C# and .NET / Performance basics: Span of T and fewer allocations

Performance basics: Span of T and fewer allocations

15 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. Final project: a notes API with EF Core, DI and logging

Measure first

Most C# code is fast enough. Before you change anything for speed, measure it. I have seen days lost on rewriting code that took two milliseconds in a request that took two seconds because of one database query. Use a profiler, or the BenchmarkDotNet library, to find where time really goes.

That said, a few habits cost nothing and pay off in hot code: parsing, formatting, loops that run millions of times. The main idea is to allocate less. Every object you create on the heap must later be cleaned by the garbage collector. Fewer allocations mean fewer collections and steadier performance.

The cost of Substring

Suppose a line holds three comma-separated numbers and you want their sum. The obvious way is Split, which allocates an array and three new strings for every line. For a million lines, that is four million small objects.

Span<T> and ReadOnlySpan<T> are views into existing memory. A ReadOnlySpan<char> can point at part of a string without copying it. Slicing it is free. Methods like int.Parse accept spans.

using System.Buffers;

string[] lines = Enumerable.Range(1, 100_000).Select(i => $"{i},{i * 2},{i * 3}").ToArray();

// Warm up so JIT costs are not measured
SumWithSplit(lines.AsSpan(0, 10));
SumWithSpan(lines.AsSpan(0, 10));

long before = GC.GetAllocatedBytesForCurrentThread();
long a = SumWithSplit(lines);
long splitBytes = GC.GetAllocatedBytesForCurrentThread() - before;

before = GC.GetAllocatedBytesForCurrentThread();
long b = SumWithSpan(lines);
long spanBytes = GC.GetAllocatedBytesForCurrentThread() - before;

Console.WriteLine($"Same result: {a == b} ({a})");
Console.WriteLine($"Split allocated ~{splitBytes / 1024} KB");
Console.WriteLine($"Span allocated  ~{spanBytes / 1024} KB");

// Slicing without copying
ReadOnlySpan<char> text = "2026-03-15";
int year = int.Parse(text[..4]);
int month = int.Parse(text[5..7]);
Console.WriteLine($"{year}/{month}");

// Small temporary buffers on the stack
Span<int> window = stackalloc int[4] { 5, 8, 2, 9 };
window.Sort();
Console.WriteLine(string.Join(",", window.ToArray()));

// Renting a bigger buffer instead of allocating one
int[] rented = ArrayPool<int>.Shared.Rent(1024);
try
{
    for (int i = 0; i < 1024; i++) rented[i] = i;
    Console.WriteLine(rented.AsSpan(0, 1024).ToArray().Sum());
}
finally
{
    ArrayPool<int>.Shared.Return(rented);
}

static long SumWithSplit(ReadOnlySpan<string> lines)
{
    long total = 0;
    foreach (string line in lines)
    {
        foreach (string part in line.Split(','))
        {
            total += long.Parse(part);
        }
    }
    return total;
}

static long SumWithSpan(ReadOnlySpan<string> lines)
{
    long total = 0;
    foreach (string line in lines)
    {
        ReadOnlySpan<char> rest = line;
        while (true)
        {
            int comma = rest.IndexOf(',');
            ReadOnlySpan<char> part = comma < 0 ? rest : rest[..comma];
            total += long.Parse(part);
            if (comma < 0) break;
            rest = rest[(comma + 1)..];
        }
    }
    return total;
}

Walking through it

The two methods compute the same sum. The first uses Split and allocates an array and strings for every line. The second walks along the line with a span. rest[..comma] is a slice, which is just a pointer and a length, and long.Parse(part) reads directly from it. Nothing is copied. The span version allocates almost nothing compared with the split version, which allocates many megabytes. Run it and compare the printed numbers. They vary a little between machines, but the gap is large.

The GC.GetAllocatedBytesForCurrentThread() call is a handy way to measure allocations in a quick experiment. For real benchmarks, use BenchmarkDotNet, which also handles warm-up and statistics.

The range syntax text[..4] and text[5..7] works on spans, so you can pick the year and month out of a date string without creating a single new string.

stackalloc reserves a small array on the stack instead of the heap. It is released automatically when the method ends. Keep it small, a few hundred bytes. A huge stack allocation crashes the program with no way to recover. For larger temporary buffers, ArrayPool<T>.Shared.Rent lends you an array and you give it back with Return. The rented array may be longer than you asked for, which is why I slice with AsSpan(0, 1024). Always return it in a finally block.

The limits of Span

Span<T> is a ref struct. It can live only on the stack. That means it cannot be a field of a normal class, cannot be used in an async method across an await, and cannot be captured by a lambda. If you need to store a slice, use Memory<T>, which is the heap-friendly cousin.

Other cheap wins

  • Use StringBuilder for building text in loops.
  • Avoid LINQ in the hottest loops. A plain for loop allocates nothing.
  • Do not convert to a list and back without a reason.
  • Cache results that are expensive and rarely change.
  • Use struct and record struct for small values, as discussed in the first lesson.

Common mistakes

  • Optimising without measuring. You will speed up the wrong thing.
  • Using stackalloc in a loop or with a size from user input. The stack is small.
  • Forgetting to return a pooled array, or using it after returning it.
  • Making code unreadable for a gain nobody can feel. Keep the clear version unless a measurement shows a real problem.

Try it yourself

  1. Write a method that counts the vowels in a string using a ReadOnlySpan<char> and no allocations.
  2. Change the example to split on a space and parse doubles. Check that results match.
  3. Install BenchmarkDotNet in a new console project and benchmark Split against the span version.
csharp
using System.Buffers;

string[] lines = Enumerable.Range(1, 100_000).Select(i => $"{i},{i * 2},{i * 3}").ToArray();

// Warm up so JIT costs are not measured
SumWithSplit(lines.AsSpan(0, 10));
SumWithSpan(lines.AsSpan(0, 10));

long before = GC.GetAllocatedBytesForCurrentThread();
long a = SumWithSplit(lines);
long splitBytes = GC.GetAllocatedBytesForCurrentThread() - before;

before = GC.GetAllocatedBytesForCurrentThread();
long b = SumWithSpan(lines);
long spanBytes = GC.GetAllocatedBytesForCurrentThread() - before;

Console.WriteLine($"Same result: {a == b} ({a})");
Console.WriteLine($"Split allocated ~{splitBytes / 1024} KB");
Console.WriteLine($"Span allocated  ~{spanBytes / 1024} KB");

// Slicing without copying
ReadOnlySpan<char> text = "2026-03-15";
int year = int.Parse(text[..4]);
int month = int.Parse(text[5..7]);
Console.WriteLine($"{year}/{month}");

// Small temporary buffers on the stack
Span<int> window = stackalloc int[4] { 5, 8, 2, 9 };
window.Sort();
Console.WriteLine(string.Join(",", window.ToArray()));

// Renting a bigger buffer instead of allocating one
int[] rented = ArrayPool<int>.Shared.Rent(1024);
try
{
    for (int i = 0; i < 1024; i++) rented[i] = i;
    Console.WriteLine(rented.AsSpan(0, 1024).ToArray().Sum());
}
finally
{
    ArrayPool<int>.Shared.Return(rented);
}

static long SumWithSplit(ReadOnlySpan<string> lines)
{
    long total = 0;
    foreach (string line in lines)
    {
        foreach (string part in line.Split(','))
        {
            total += long.Parse(part);
        }
    }
    return total;
}

static long SumWithSpan(ReadOnlySpan<string> lines)
{
    long total = 0;
    foreach (string line in lines)
    {
        ReadOnlySpan<char> rest = line;
        while (true)
        {
            int comma = rest.IndexOf(',');
            ReadOnlySpan<char> part = comma < 0 ? rest : rest[..comma];
            total += long.Parse(part);
            if (comma < 0) break;
            rest = rest[(comma + 1)..];
        }
    }
    return total;
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account