Skip to main content

Lesson 6 of 8

Response Compression & Minimizing Allocations

Reducing allocations is the single most impactful performance improvement for high-QPS ASP.NET Core APIs. Allocation pressure triggers more GC runs, causing request pauses. ArrayPool, Span<T>, and MemoryPool eliminate many common allocations in hot paths.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Zero-Allocation Patterns with Span<T> & ArrayPool

Zero-Allocation Patterns with Span<T> & ArrayPool
using System.Buffers;

// ━━ ArrayPool - reuse arrays instead of new byte[n] ━━
// Allocates from OS once, then lends to callers and reclaims
public class CsvParser
{
    public List<string[]> ParseCsv(Stream stream)
    {
        // ❌ BAD: allocates new 4096-byte array on every call
        var buffer = new byte[4096];

        // ✅ GOOD: rents from pool - no GC pressure
        var buffer2 = ArrayPool<byte>.Shared.Rent(4096);
        try
        {
            var bytesRead = stream.Read(buffer2, 0, buffer2.Length);
            // process buffer2[0..bytesRead]
            return [];
        }
        finally
        {
            ArrayPool<byte>.Shared.Return(buffer2, clearArray: true); // return to pool
        }
    }
}

// ━━ Span<T> - slice without allocation ━━
public static ReadOnlySpan<char> ExtractSlug(ReadOnlySpan<char> url)
{
    // Parse "https://myapp.com/api/products/my-product-slug" → "my-product-slug"
    // No string allocation - operates on the original memory
    var lastSlash = url.LastIndexOf('/');
    return lastSlash < 0 ? url : url[(lastSlash + 1)..];
}

// ━━ StringBuilder vs string concatenation ━━
// ❌ BAD: each + allocates a new string
var bad = "Hello " + name + "! You have " + count + " messages.";

// ✅ GOOD: StringBuilder writes to preallocated buffer
var sb = new System.Text.StringBuilder(capacity: 100);
sb.Append("Hello ").Append(name).Append("! You have ").Append(count).Append(" messages.");
var good = sb.ToString(); // single allocation at the end

// ✅ BETTER: string interpolation is optimized by compiler for simple cases
var best = $"Hello {name}! You have {count} messages."; // compiler-optimized

// ━━ Minimize closures in LINQ hot paths ━━
// ❌ BAD: captures local variable → heap allocation per call
int minPrice = 10;
var expensive = products.Where(p => p.Price > minPrice); // closure allocation

// ✅ GOOD: static lambda (known at compile time - no capture)
var highValue = products.Where(static p => p.Price > 10);

// ━━ Record structs for high-frequency small data ━━
// Class: heap-allocated, GC pressure, reference semantics
// Record struct: stack-allocated, zero GC, value semantics
public readonly record struct ProductId(Guid Value)
{
    public static ProductId New() => new(Guid.NewGuid());
    public override string ToString() => Value.ToString("N");
}

// ━━ Benchmark with BenchmarkDotNet ━━
// dotnet add package BenchmarkDotNet
// [MemoryDiagnoser] attribute shows allocations per operation
// Run: dotnet run -c Release -- --filter '*'

class products : System.Collections.Generic.List<dynamic> { }

Tip

Tip

Practice Response Compression Minimizing Allocations in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Response Compression Minimizing Allocations from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Response Compression Minimizing Allocations is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done