skip to content

In a C# hot path, when does a local function that captures locals allocate nothing, and what makes it heap-allocate like a lambda?

level: seniorimportance: should knowfreq 32%

answer

  1. closure environment: struct or class
  2. passed by ref as a hidden parameter
  3. delegate conversion forces a class
  4. captures shared with a lambda
  5. async or iterator local functions

basics

~20 s

Called directly, never converted to a delegate, and sharing no captures with a lambda, it keeps captures in a struct passed by reference: no allocation. A delegate conversion, a sharing lambda, or an async or iterator local function forces a heap closure class.

solid answer

~50 s

The compiler gathers captured variables into a generated closure type. For a lambda that type is always a class, because a lambda is always a delegate, and the delegate needs a heap object to point at. For a local function that is only called, the compiler can make it a `struct` that lives as a local of the enclosing method and pass it to the function as a hidden `ref` parameter, so the call allocates nothing and writes stay visible on both sides. The struct is lost when the function is converted to a delegate (passed as a method group such as `sizes.Count(IsLarge)`), when a lambda or delegate-converted function captures variables from the same scope, or when the local function is `async` or an iterator, which cannot take `ref` parameters. In those cases you pay a closure object plus, for the conversion, a delegate.

code

csharp · 31 lines
csharp
using System;
using System.Linq;

int[] sizes = [120, 4_096, 75, 9_000];
Measure("called only", () => Scan.CallOnly(sizes, 1_000));
Measure("converted to a delegate", () => Scan.AsDelegate(sizes, 1_000));

static void Measure(string label, Func<int> run)
{
    run();
    long before = GC.GetAllocatedBytesForCurrentThread();
    for (int i = 0; i < 100_000; i++) run();
    Console.WriteLine($"{label}: {(GC.GetAllocatedBytesForCurrentThread() - before) / 100_000} bytes per call");
}

static class Scan
{
    public static int CallOnly(int[] sizes, int threshold)
    {
        int count = 0;
        foreach (var s in sizes) if (IsLarge(s)) count++;
        return count;
        bool IsLarge(int size) => size > threshold;   // struct closure, passed by ref
    }

    public static int AsDelegate(int[] sizes, int threshold)
    {
        return sizes.Count(IsLarge);                  // method group -> Func<int, bool>
        bool IsLarge(int size) => size > threshold;   // class closure + delegate
    }
}

go deeper

for a junior

Recall that capturing a local means the compiler stores it in a generated closure, and that a lambda's closure always lives on the heap.

for a middle

Explain the struct environment passed by ref to a directly called local function, and why writes stay visible on both sides.

for a senior

Name the three triggers that bring the heap closure back (delegate conversion, a sharing lambda, async or iterator) and prove the fix with an allocation measurement.

for a principal

Decide where allocation discipline is worth enforcing: hot paths and libraries justify static local functions and review rules; ordinary application code rarely does.

## How a capturing local function is lowered When a lambda or local function uses a local variable or parameter of its enclosing method, that variable is **captured**: both the method and the nested function must see the same storage. The compiler's closure conversion moves each captured variable into a **closure environment**, a generated type (named like `<>c__DisplayClass0_0`) whose fields replace the locals. - For a **lambda**, the environment is always a **class**. The lambda becomes a delegate whose target is an instance of that class, so the class instance and the delegate are both heap allocations. - For a **local function** that is only called directly, the environment can be a **struct**. It is a plain local of the enclosing method, and the local function receives it as a hidden `ref` parameter. No heap allocation is needed, and because it is passed by reference, writes made inside the function are seen by the method and vice versa. The C# documentation calls the class-or-struct choice an implementation detail; the Roslyn compiler shipped in the .NET 10 SDK makes it as described below. ## What forces a class The compiler decides per scope. It keeps the struct only when every function capturing that scope's variables could take a `ref` parameter. The main cases that turn it into a class: 1. **Delegate conversion.** Passing the local function as a method group (`sizes.Count(IsLarge)`), assigning it to a `Func<int, bool>`, or subscribing it to an event converts it to a delegate. A delegate's signature cannot gain a hidden `ref` parameter, so the environment becomes a class, and the conversion allocates a delegate on top. 2. **Sharing with a lambda.** If a lambda, or another local function that is converted to a delegate, captures any variable from the same scope, the whole environment for that scope becomes a class, and the "pure" local function now pays for it too, even though it is only called. 3. **async or iterator local functions.** These cannot take `ref` parameters, so their captures go in a class. The compiler also keeps a class in a rarer case: code inside a generic interface with variant (`in` or `out`) type parameters. ## Measuring it The snippet below calls a capturing local function directly in one method and passes it as a method group in another, then reads `GC.GetAllocatedBytesForCurrentThread()` around 100,000 calls. | Usage of the local function | Closure type | Measured per call (64-bit, .NET 10) | |---|---|---| | Called directly | struct, passed by `ref` | 0 bytes | | Passed to `Enumerable.Count` as a method group | class plus `Func<int, bool>` | 88 bytes | | Called directly, but a lambda captures the same local | class | 88 bytes (closure plus the lambda's delegate) | ## Guarding the zero-allocation path - Keep the local function **called, never converted**: no method groups, no event subscriptions, no assignment to a delegate variable. - Do not let a **lambda capture** the same variables in that method; move the lambda's work into another local function or pass values as arguments. - Where the function needs no outer state at all, mark it **`static`** (C# 8). It then captures nothing, so there is no environment to allocate, and converting it to a delegate allocates a cached delegate once, since C# 11 caches method group conversions of static methods. - Verify with an allocation measurement, not intuition: `GC.GetAllocatedBytesForCurrentThread()` in a quick test, or a memory-diagnosing benchmark. ## Reading the generated code The difference is visible in the compiled assembly. In the snippet, the struct environment for `CallOnly` shows up as a nested value type, and the local function's generated method takes it as a by-reference parameter. The environment for `AsDelegate` is a nested class, the local function becomes an instance method on that class, and the call site creates a `Func<int, bool>` pointing at it. Reflection over the containing type's non-public nested types, checking `Type.IsValueType`, is enough to see which one you got. ## Why this matters on a hot path A method that runs per request or per frame and builds a closure on every call adds steady garbage-collector pressure for nothing. Local functions give the readability of a nested helper with the cost of a plain method call, but only while the conditions above hold. A small, innocent edit, such as passing the helper to a LINQ operator or adding a lambda that reads the same local, silently brings the allocation back, which is why reviewers check how a local function is used, not just that one is used.

  • In C#, does marking such a local function static change what it allocates?
    A `static` local function cannot capture, so the values it needs become parameters and there is no closure environment at all. Called directly it allocates nothing. Converted to a delegate it allocates the delegate once: since C# 11 the compiler caches method group conversions of static methods, and a measured loop shows 0 bytes per call after the first.
  • In C#, how can you check which closure type the compiler generated for a method?
    Look at the compiled output: the generated environment is a nested type named like `<>c__DisplayClass0_0`, and reflection's `Type.IsValueType` tells you whether it is a struct. A local function using a struct environment takes it as a `ref` parameter, visible in its generated signature. An allocation measurement around many calls confirms the effect.

  • Local functions never allocate, whatever they capture or however they are used.
  • Any captured variable always means a heap closure, local function or lambda.
  • Passing a local function as a method group is free because it has a name.
  • A struct closure copies captured variables, so writes inside the function are lost.
  • A local function must be static for the compiler to use a struct closure.