📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how you would reduce allocations on a hot path in a .NET 10 service. Use spans, pooling, string.Create and removing LINQ and closures where they matter, and prove the improvement with BenchmarkDotNet.

Practical allocation reduction on a hot path with Span<T>, ArrayPool<T>, string.Create and removing LINQ and closure allocations, measured with BenchmarkDotNet's MemoryDiagnoser.

Mid-Level Coding Intermediate allocations arraypool benchmarkdotnet gc performance span

🎯 Key points

  • Find the hot path first: profile shows high alloc-rate from a specific method
  • Why it matters: more allocations mean more Gen 0 GCs, more promotions and Gen 2/LOH pauses that hurt p99 and throughput
  • BenchmarkDotNet with [MemoryDiagnoser] reports Mean and Allocated per operation
  • ReadOnlySpan<char> slicing instead of Substring/Split
  • string.Create or stackalloc + TryFormat for building strings without intermediates
  • ArrayPool<T>.Shared.Rent/Return in try/finally for temporary buffers
  • Replace LINQ and capturing lambdas in tight loops with plain loops; keep readability on cold paths
  • Verify in production: alloc-rate, time-in-gc and p99

⏱ 30-second answer

First I prove the method is hot: dotnet-counters shows a high allocation rate and an allocation profile points at it. Then I write a BenchmarkDotNet benchmark with [MemoryDiagnoser] so every change shows Mean and Allocated bytes.

The usual fixes:

  • ReadOnlySpan<char> slicing instead of Substring and Split, which allocate a string per piece.
  • string.Create (or stackalloc plus TryFormat) to build the final string once.
  • ArrayPool<T>.Shared for temporary buffers, returned in finally.
  • Plain loops instead of LINQ and capturing lambdas in tight loops (enumerator and closure allocations).

The trade-off is readability: span-based code is harder to maintain, so I only do it where the profile and the benchmark justify it.

🗣 Full answer (senior)

How I would answer this in an interview

"I only do this after a profile tells me a method is hot. Typically dotnet-counters shows an allocation rate of hundreds of megabytes a second, time in GC is high, and an allocation trace in Visual Studio or PerfView points at one method, often a parser or a formatter called for every request or message.

I then write a BenchmarkDotNet benchmark with [MemoryDiagnoser] and the current code as the baseline. Allocations on hot paths usually come from four places: Substring and Split creating a string per token, string concatenation or interpolation creating intermediates, temporary arrays and lists, and LINQ or lambdas that capture variables, which allocate an enumerator, a closure object and a delegate. The fixes are parsing with ReadOnlySpan<char> and int.Parse(ReadOnlySpan<char>), building output with string.Create or a stack buffer and TryFormat, renting temporary arrays from ArrayPool<T>.Shared and returning them in a finally, and replacing LINQ in the inner loop with a foreach or a span loop.

The mistake I see is applying these everywhere. A Split in a controller that runs once per request is fine; the same Split in a loop over a million rows isn't. I keep the optimised version small, covered by tests that compare it with the simple version, and I verify the win in production by watching allocation rate and p99, not just the benchmark."


Allocation sources and replacements

Source Allocates Replacement
line.Split(',') string[] plus one string per field ReadOnlySpan<char> + IndexOf, or MemoryExtensions.Split into Span<Range>
s.Substring(a, b) New string s.AsSpan(a, b)
a + "-" + b in a loop Intermediate strings string.Create, StringBuilder, interpolated handler into a span
new byte[4096] per call Array (LOH if > 85 KB) ArrayPool<byte>.Shared.Rent / stackalloc for small sizes
items.Where(x => x.Id == id) Closure, delegate, enumerator foreach with a local comparison
value.ToString() then append String value.TryFormat(span, out var written)
Boxing (object, non-generic interfaces) Box per value Generics, IEquatable<T>

Example benchmark result

Method Mean Allocated
ParseWithSplit (baseline) 412 ns 616 B
ParseWithSpan 96 ns 0 B
FormatWithConcat (baseline) 188 ns 216 B
FormatWithStringCreate 61 ns 64 B

(Illustrative numbers from a typical laptop; always run on your own hardware.)

Production example

A message consumer parsed 40,000 CSV lines a second with Split and LINQ, allocating about 700 MB/s with 15% time in GC. A span-based parser plus a pooled output buffer dropped allocations to 35 MB/s, time in GC to under 2%, and let the same pod count handle 2.5 times the throughput.

🔍 What the interviewer is checking

Checks whether the candidate can reduce allocations with modern APIs and prove the gain, without over-applying the techniques.

Green flags

  • Starts from a profile and writes a benchmark with MemoryDiagnoser
  • Knows the rent/return rules of ArrayPool
  • Explains why closures and LINQ allocate
  • Verifies the win in production metrics

Red flags

  • Applies spans everywhere 'for performance'
  • No measurement, or benchmarks in Debug
  • Uses pooled arrays after returning them

📚 Learn in depth

1. Why allocations cost time

Allocation itself is cheap: a pointer bump in the thread's allocation context. The cost comes later. Every ~few MB of Gen 0 allocation triggers a GC; survivors are copied to Gen 1 and Gen 2; Gen 2 and LOH collections are expensive and cause latency spikes. Fewer allocations mean fewer GCs and a lower p99.

alloc-rate  -->  Gen0 GC frequency  -->  promotions  -->  Gen2 GCs  -->  p99 spikes

2. Spans

Span<T> and ReadOnlySpan<T> are ref structs that describe a window over existing memory (array, string, stack, native). Slicing a span is just a new (pointer, length) pair: no copy, no allocation. Because they're stack-only they can't be stored on the heap or cross an await; use Memory<T> there. Most BCL parsing and formatting APIs have span overloads: int.Parse(ReadOnlySpan<char>), TryFormat, Utf8Formatter, Encoding.GetBytes(ReadOnlySpan<char>, Span<byte>).

3. string.Create

string.Create(length, state, (span, state) => ...) allocates the final string once and gives you its buffer as a Span<char> to fill. Pass state explicitly (often a tuple) so the lambda is static and allocates no closure.

4. ArrayPool

ArrayPool<T>.Shared keeps per-core buckets of arrays by power-of-two size. Rent(n) may return a larger array; always use the length you asked for. Return in a finally; never use the array after returning it; pass clearArray: true if it held sensitive data. For small, fixed sizes, stackalloc into a Span<T> is cheaper (keep it under ~1 KB and never in a loop).

5. LINQ and closures

A lambda that captures a local compiles to a display class allocated on each call, plus a delegate. LINQ over IEnumerable<T> allocates an enumerator per operator. .NET 9 and 10 made LINQ much faster for arrays and lists, but in a tight loop a foreach still allocates nothing. Use static lambdas to make the compiler stop you capturing by accident.

6. Measuring correctly

BenchmarkDotNet runs warm-up, pilot and measurement phases, forces Release builds and reports statistics. [MemoryDiagnoser] adds Gen0 collections and Allocated per operation. Return results from benchmarks so the JIT can't remove the work as dead code.

Try it yourself

  1. Run the benchmark below and compare Mean and Allocated.
  2. Add a [Params(10, 1000)] for the number of fields and see where the span version's lead grows.
  3. Change the lambda in a LINQ query to static and fix the compile errors it reveals.
  4. Use dotnet-counters on a sample API before and after replacing Split in a hot loop, and record alloc-rate.
  5. Deliberately use a rented array after Return in a test and see the corruption it can cause.

💻 Code

Before and after for a hot CSV-style parser and formatter, with the BenchmarkDotNet harness that proves the change.

// LineParser.cs
using System.Buffers;
using System.Text;

namespace Perf.Parsing;

public readonly record struct Reading(int SensorId, int Value);

public static class LineParser
{
    // Before: Split allocates a string[] plus a string per field.
    public static Reading ParseWithSplit(string line)
    {
        var parts = line.Split(',');
        return new Reading(int.Parse(parts[0]), int.Parse(parts[1]));
    }

    // After: slice the span; int.Parse has a ReadOnlySpan<char> overload. Zero allocations.
    public static Reading ParseWithSpan(string line)
    {
        ReadOnlySpan<char> span = line;
        var comma = span.IndexOf(',');
        return new Reading(int.Parse(span[..comma]), int.Parse(span[(comma + 1)..]));
    }

    // Before: two ToString() intermediates, then a concatenated result string.
    public static string FormatWithConcat(Reading r) => r.SensorId.ToString() + ":" + r.Value.ToString();

    // After: format into a small stack buffer, then allocate only the final string.
    public static string FormatWithStackBuffer(Reading r)
    {
        Span<char> buffer = stackalloc char[23]; // two ints (max 11 chars each) + ':'
        r.SensorId.TryFormat(buffer, out var written);
        buffer[written++] = ':';
        r.Value.TryFormat(buffer[written..], out var second);
        return new string(buffer[..(written + second)]);
    }

    // Temporary buffer from the pool, always returned in finally.
    public static int ChecksumUtf8(string text)
    {
        var max = Encoding.UTF8.GetMaxByteCount(text.Length);
        var buffer = ArrayPool<byte>.Shared.Rent(max);
        try
        {
            var count = Encoding.UTF8.GetBytes(text, buffer);
            var sum = 0;
            foreach (var b in buffer.AsSpan(0, count)) sum += b; // only the bytes we wrote
            return sum;
        }
        finally
        {
            ArrayPool<byte>.Shared.Return(buffer);
        }
    }
}
// ParserBenchmarks.cs: dotnet run -c Release
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Perf.Parsing;

BenchmarkRunner.Run<ParserBenchmarks>();

[MemoryDiagnoser]
public class ParserBenchmarks
{
    private const string Line = "48213,1772";
    private static readonly Reading Sample = new(48213, 1772);

    [Benchmark(Baseline = true)] public Reading Split() => LineParser.ParseWithSplit(Line);
    [Benchmark] public Reading Span() => LineParser.ParseWithSpan(Line);
    [Benchmark] public string Concat() => LineParser.FormatWithConcat(Sample);
    [Benchmark] public string StackBuffer() => LineParser.FormatWithStackBuffer(Sample);
}

For variable-length output where you can compute the length up front, string.Create(length, state, static (span, s) => ...) goes one step further and writes directly into the final string's buffer.

⚠ Common mistakes

  • Mistake: Optimising without measuring. Why it is wrong: You add complex span code where allocations weren't the problem. Instead: Confirm with alloc-rate, an allocation profile and a benchmark.
  • Mistake: Micro-optimising cold paths. Why it is wrong: Code that runs once per request rarely matters, and the span version costs readability. Instead: Limit this to methods the profiler shows as hot.
  • Mistake: Using the full length of a rented array. Why it is wrong: Rent(100) can return 128 elements with stale data. Instead: Track the requested length and slice.
  • Mistake: Using a pooled array after Return. Why it is wrong: Another caller may already own it, leading to corrupted or leaked data. Instead: Return once, in finally, and drop the reference.
  • Mistake: stackalloc with a size from user input or inside a loop. Why it is wrong: A stack overflow kills the process. Instead: Use a small constant threshold and fall back to ArrayPool.
  • Mistake: Benchmarks that discard their result. Why it is wrong: The JIT can eliminate the work and report impossible numbers. Instead: Return the result from the benchmark method.
  • Mistake: Trusting the benchmark alone. Why it is wrong: A micro-win can be invisible end to end. Instead: Check alloc-rate, time in GC and p99 in production.

🏛 Senior insight: trade-offs

Allocation reduction is a targeted tool: on a typical line-of-business API, the database dominates and this work moves nothing. It pays off in high-throughput parsers, serialisers, middleware, logging and message consumers. Prefer framework features first: System.Text.Json source generation, SearchValues<T>, CollectionsMarshal, and the span overloads the BCL already has. Keep the simple version in tests as an oracle for the optimised one.

Technique When it fits Cost When not to
Span slicing Parsing strings and bytes in hot loops Can't cross await or live on the heap Code that needs to store pieces
string.Create Building many small strings of known length More complex code One-off messages
ArrayPool Temporary buffers > ~1 KB Rent/return discipline; misuse leaks data Buffers that escape the method
Remove LINQ Inner loops over large collections Less declarative code Request-level queries over small lists

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Span<T> Why: Checks they understand span's ref struct limits and where it can point
    How to answer

    Span<T> is a ref struct holding a reference and a length: a typed, bounds-checked view over contiguous memory, whether that memory is an array, a stackalloc buffer, native memory or part of a string (through ReadOnlySpan<char>). Slicing (span[2..6], Slice) creates a new view without copying, so parsers and formatters can work on pieces of a buffer with no allocations. Because it can point at the stack, it is stack-only: it cannot be a field of a class, be boxed, be captured by a lambda, or live across await/yield (C# 13 allows span locals in async and iterator methods as long as they do not cross those points). Helpers in MemoryExtensions (IndexOf, SequenceEqual, Sort, Trim) are vectorised. CollectionsMarshal.AsSpan(list) exposes a list's backing array, but adding to the list invalidates it.

  2. When: Candidate mentions ArrayPool Why: Checks they know the data-leak and corruption risks of pool misuse
    How to answer

    Pooling bugs are lifetime bugs: the pool gives a returned array to the next renter, so any code still using it reads or writes someone else's data. The usual causes are use after return (returning in finally while an async continuation, a queued Memory<T> or a lazy enumerable still uses the array), double return (two renters then share one array), treating array.Length as the data length (Rent returns an array at least as large as requested, with old contents), not clearing buffers that held secrets (Return(array, clearArray: true)), and returning arrays not rented from that pool. To debug: reproduce under concurrency, add canaries or a poisoning wrapper pool in tests that fills returned arrays with a marker and detects double returns, trace System.Buffers.ArrayPoolEventSource events, and review every rent for a single owner and a single return in finally.

  3. When: Candidate mentions hidden allocations Why: Checks they can find and remove boxing
    How to answer

    Boxing wraps a value type in a new heap object so it can be used as object or an interface; unboxing checks the object's type and copies the value back, and it must be the exact type or you get InvalidCastException. Every box is a heap allocation, so in hot paths it creates GC pressure. Hidden boxing comes from non-generic APIs like ArrayList and params object[], passing structs as interfaces, calling GetType() or non-overridden Equals/GetHashCode on structs, and enumerating a List<T> through IEnumerable<T>. I find it with BenchmarkDotNet's MemoryDiagnoser or an allocation profiler and fix it with generics, constraints and IEquatable<T>.

🛠 Real-world problems: how you handle them

Message consumer spending 15% of its time in GC from CSV parsing
Situation
A telemetry ingestion worker on AKS parsed [40,000] CSV lines per second from Azure Service Bus. Pods were scaled to [12] to keep up, and costs were rising.
Signals
dotnet-counters showed alloc-rate around [700 MB/s], time-in-gc at [15%], frequent Gen 1 collections; consumer lag grew at peak; p99 processing time spiked every few seconds.
Investigation
Captured an allocation trace with dotnet-trace (gc-verbose profile) and opened it in PerfView: 70% of allocated bytes came from String.Split and LINQ Select in the parser, plus a new byte[] per message. Wrote BenchmarkDotNet benchmarks for the parser with MemoryDiagnoser as a baseline.
Resolution
Rewrote the parser with ReadOnlySpan<char> slicing and span-based int/decimal parsing, replaced LINQ with a loop, and rented message buffers from ArrayPool. The benchmark showed 0 B allocated per line versus 600 B. Released behind a feature flag and compared metrics.
Prevention
Kept the old parser as a test oracle with property-based tests; added the benchmark to a nightly BenchmarkDotNet run with a regression threshold; added an alloc-rate panel and alert to the service dashboard.

How to tell it (STAR)

**S:** At [company] our ingestion worker needed [12] pods to keep up and spent about [15%] of its time in garbage collection. **T:** I was asked to cut the cost without a rewrite. **A:** I measured first: dotnet-counters showed [700 MB/s] of allocations, and a PerfView allocation trace pinned most of it on Split and LINQ in the parser. I wrote a BenchmarkDotNet baseline, rebuilt the parser with spans and pooled buffers, kept the old parser as a test oracle, and shipped behind a flag. **R:** Allocations fell to [35 MB/s], time in GC under [2%], and we handled the same load with [5] pods, saving about [$X] a month.

↩ Usually asked after

More in Application Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me