Performance

suggest change

Modern .NET is engineered for high-throughput, low-latency execution. Optimizing C# performance revolves primarily around reducing heap allocations to minimize Garbage Collection (GC) pauses, leveraging CPU cache locality, and utilizing zero-allocation primitives like Span<T> and ValueTask<T>.


1. Zero-Allocation Slicing with Span<T> and ReadOnlySpan<T>

Historically, string manipulations like .Substring() or .Split() allocated new string objects on the managed heap. Span<T> and ReadOnlySpan<T> represent contiguous regions of arbitrary memory (stack, heap, or native) that can be sliced without copying or allocating.

using System;

class SpanParsingExample
{
    // Extracts area code from "(555) 123-4567" without allocating a new substring
    public static ReadOnlySpan<char> ExtractAreaCode(ReadOnlySpan<char> phoneNumber)
    {
        int openParen = phoneNumber.IndexOf('(');
        int closeParen = phoneNumber.IndexOf(')');

        if (openParen != -1 && closeParen > openParen)
        {
            return phoneNumber.Slice(openParen + 1, closeParen - openParen - 1);
        }

        return ReadOnlySpan<char>.Empty;
    }

    // Zero-allocation number parsing directly from ReadOnlySpan<char>
    public static int ParseLeadingInteger(ReadOnlySpan<char> text)
    {
        int spaceIndex = text.IndexOf(' ');
        ReadOnlySpan<char> token = spaceIndex >= 0 ? text.Slice(0, spaceIndex) : text;

        if (int.TryParse(token, out int result))
        {
            return result;
        }

        return -1;
    }
}

2. Reducing GC Pressure with ArrayPool<T>

Allocating large temporary buffers (especially arrays larger than 85,000 bytes, which land on the Large Object Heap and cause severe fragmentation) degrades throughput. System.Buffers.ArrayPool<T> rents pre-allocated arrays and returns them after use:

using System;
using System.Buffers;
using System.IO;

public static void ProcessLargeFile(string path)
{
    // Rent a reusable 64 KB buffer
    byte[] buffer = ArrayPool<byte>.Shared.Rent(65536);

    try
    {
        using var stream = File.OpenRead(path);
        int bytesRead;

        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            // Process rented chunk...
        }
    }
    finally
    {
        // Always return buffer in a finally block
        ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
    }
}

3. High-Performance Async with ValueTask<T>

A standard Task<T> is a reference type allocated on the heap every time an asynchronous method is invoked. When an operation frequently completes synchronously (such as reading from an in-memory cache), ValueTask<T> avoids this allocation entirely:

using System.Collections.Concurrent;
using System.Threading.Tasks;

public class CachedUserRepository
{
    private readonly ConcurrentDictionary<int, string> _cache = new();

    public ValueTask<string?> GetUserNameAsync(int userId)
    {
        // Fast path: Synchronous completion incurs ZERO heap allocation
        if (_cache.TryGetValue(userId, out string? cachedName))
        {
            return new ValueTask<string?>(cachedName);
        }

        // Slow path: Calls remote database and returns asynchronous task
        return new ValueTask<string?>(FetchFromDatabaseAsync(userId));
    }

    private async Task<string?> FetchFromDatabaseAsync(int userId)
    {
        await Task.Delay(50); // Simulate network I/O
        string name = $"User_{userId}";
        _cache[userId] = name;
        return name;
    }
}

4. Avoiding Boxing of Structs

Boxing occurs when a value type (struct, int, enum) is cast to an object or interface, causing a heap allocation:

// INEFFICIENT: Boxing occurs because int is cast to object
object boxed = 42;
Console.WriteLine(string.Format("Value: {0}", 42)); // Boxes the int (object parameter), even in modern .NET

// EFFICIENT: Modern string interpolation with DefaultInterpolatedStringHandler avoids boxing
Console.WriteLine($"Value: {42}");

// Generics with struct constraints avoid boxing interfaces:
public void ProcessItem<T>(T item) where T : struct, IComparable<T>
{
    // T is constrained; no boxing occurs when calling CompareTo
}

5. Pre-allocating Collection Capacities

Resizing a List<T> or Dictionary<TKey, TValue> doubles internal array capacity, copying all elements to a new array and creating garbage:

using System.Collections.Generic;

// BAD: Triggers multiple reallocations and copies as elements are added
var items = new List<int>();
for (int i = 0; i < 100_000; i++) items.Add(i);

// GOOD: Single allocation upfront
var optimizedItems = new List<int>(capacity: 100_000);
for (int i = 0; i < 100_000; i++) optimizedItems.Add(i);

6. Measuring Accurately with BenchmarkDotNet

Never optimize based on intuition alone. BenchmarkDotNet is the standard benchmarking library for .NET, handling JIT warmup, loop unrolling, and memory diagnostics:

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

[MemoryDiagnoser] // Measures allocated bytes and GC Gen 0/1/2 counts
public class StringParserBenchmark
{
    private const string RawInput = "User:Alice;ID:1004;Status:Active";

    [Benchmark(Baseline = true)]
    public string ParseWithSubstring()
    {
        int start = RawInput.IndexOf("ID:") + 3;
        int end = RawInput.IndexOf(';', start);
        return RawInput.Substring(start, end - start);
    }

    [Benchmark]
    public ReadOnlySpan<char> ParseWithSpan()
    {
        ReadOnlySpan<char> span = RawInput.AsSpan();
        int start = span.IndexOf("ID:") + 3;
        int end = span.Slice(start).IndexOf(';');
        return span.Slice(start, end);
    }
}

7. Performance Best Practices Checklist

  1. Measure First: Use BenchmarkDotNet and dotnet-trace / dotnet-dump before refactoring for performance.
  2. Favor Span<T> and Memory<T>: Avoid allocating intermediary strings or array slices.
  3. Reuse Buffers: Use ArrayPool<T>.Shared for buffers larger than a few kilobytes.
  4. Use ValueTask<T>: For asynchronous APIs where results are frequently available synchronously (e.g. caches or buffered streams).
  5. Pre-size Collections: Always specify initial capacity when the collection item count is known or estimable.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents