skip to content

A C# order filter on a hot path calls orders.Exists(o => o > threshold) on every request; what does each call allocate, and how do static lambdas help?

level: seniorimportance: should knowfreq 45%

answer

  1. capturing vs non-capturing
  2. closure object plus delegate
  3. allocated at scope entry
  4. pass state, do not capture it

basics

~20 s

Capturing threshold costs a closure object and a new delegate on every call; a non-capturing lambda's delegate is cached and reused. A static lambda (C# 9) makes any accidental capture a compile error, so state must be passed as an argument.

solid answer

~40 s

Because the lambda captures the `threshold` parameter, every call allocates a **closure object** for it and a **new delegate** pointing at that object; on a 64-bit .NET 10 runtime that measures 96 bytes per call with `List<T>.Exists`. The closure object is created when execution enters the scope that declares the captured variable, here the method itself, so an early `return` before the lambda still pays for it. A lambda that captures nothing is compiled to a delegate cached in a static field after first use, so it allocates nothing per call. Marking a lambda `static` (C# 9) adds no speed of its own; it turns any capture of a local, parameter or `this` into CS8820 or CS8821, which forces the state through an API that accepts it as an argument.

code

csharp · 32 lines
csharp
var orders = new List<decimal> { 50m, 120m, 300m };
var none = new List<decimal>();

static bool AnyAbove(List<decimal> orders, decimal threshold) =>
    orders.Exists(o => o > threshold);                  // captures threshold

static bool AnyAboveState(List<decimal> orders, decimal threshold) =>
    Exists(orders, threshold, static (o, t) => o > t);  // captures nothing

static bool Exists<TState>(List<decimal> items, TState state, Func<decimal, TState, bool> test)
{
    foreach (var item in items) if (test(item, state)) return true;
    return false;
}

static bool Early(List<decimal> orders, decimal threshold)
{
    if (orders.Count == 0) return false;                // no lambda on this path
    return orders.Exists(o => o > threshold);
}

static long BytesPerCall(Func<bool> body)
{
    body();                                              // warm up
    long before = GC.GetAllocatedBytesForCurrentThread();
    for (int i = 0; i < 1000; i++) body();
    return (GC.GetAllocatedBytesForCurrentThread() - before) / 1000;
}

Console.WriteLine($"capturing lambda: {BytesPerCall(() => AnyAbove(orders, 100m))} B/call");
Console.WriteLine($"static lambda:    {BytesPerCall(() => AnyAboveState(orders, 100m))} B/call");
Console.WriteLine($"early return:     {BytesPerCall(() => Early(none, 100m))} B/call");

go deeper

for a junior

Recall that a lambda which uses a local or parameter is not free: it creates objects every time the code runs.

for a middle

Explain the difference between a cached non-capturing delegate and a capturing lambda's closure object plus new delegate.

for a senior

Diagnose allocation in a hot path from the code, including the closure created at scope entry, and fix it with static lambdas and state-passing overloads after measuring.

for a principal

Set where allocation rules apply, such as per-frame or per-request hot paths, and keep them out of ordinary code where readability matters more.

## What a capturing lambda costs In a request-handling path that runs thousands of times a second, this line looks free: ```csharp static bool AnyAbove(List<decimal> orders, decimal threshold) => orders.Exists(o => o > threshold); ``` It is not. The lambda uses the parameter `threshold`, so the compiler: 1. allocates a **closure object** (a compiler-generated class with a `threshold` field) when the method's scope is entered; 2. allocates a **new delegate** of type `Predicate<decimal>` whose `Target` is that closure object, each time the lambda expression is evaluated. Measured with `GC.GetAllocatedBytesForCurrentThread` on the .NET 10 runtime (64-bit), that is **96 bytes per call**: 32 for the closure object holding a `decimal`, 64 for the delegate. `List<T>.Exists` itself allocates nothing. ## Three lambdas, three costs | Lambda | What is allocated per evaluation | |---|---| | Captures nothing: `o => o > 100m` | nothing after the first call; the delegate is cached in a static field | | Captures only `this` (reads a field) | a new delegate whose `Target` is the instance; no closure class | | Captures a local or parameter | a closure object for the scope, plus a new delegate | The non-capturing case is a **compiler optimisation**, not a language guarantee: Roslyn stores the delegate in a static field of a hidden class on first use and reuses it. A lambda that captures only `this` cannot be cached that way, because each instance needs its own `Target`. ## The early-return trap The closure object is created **when execution enters the scope that declares the captured variable**, not when the lambda is reached: ```csharp static bool Early(List<decimal> orders, decimal threshold) { if (orders.Count == 0) return false; // still allocates the closure object return orders.Exists(o => o > threshold); } ``` Because `threshold` is a parameter, its scope is the whole method, so every call allocates the 32-byte closure object, even on the empty-list path that never creates the delegate. The fixes are to move the lambda into a separate method that is called only on the slow path, or to stop capturing. ## What static lambdas do and do not do **C# 9** added the `static` modifier for lambdas and anonymous methods. Its contract, from the language proposal: - a static lambda **cannot reference locals, parameters or `this`** from the enclosing scope; the compiler reports **CS8820** ("A static anonymous function cannot contain a reference to 'threshold'.") or **CS8821** for `this` or `base`; - it **may** reference static members and constants; - **no guarantee** is made about whether it is emitted as a static method in metadata. So `static` is a **guard**, not an optimisation. A non-capturing lambda already gets the cached delegate whether or not it is marked `static`. What `static` buys is that a later edit which adds a capture, and silently brings the allocation back, fails to compile instead of shipping. ## Getting the state in without capturing it Once a lambda may not capture, the state has to travel as an argument. Many APIs provide a state-passing overload for this reason (for example `ConcurrentDictionary<TKey, TValue>.GetOrAdd<TArg>` takes a factory argument). For your own helpers, add a generic state parameter: ```csharp static bool Exists<TState>(List<decimal> items, TState state, Func<decimal, TState, bool> test) ``` and call it with `Exists(orders, threshold, static (o, t) => o > t)`. The measured cost drops to **0 bytes per call**. ## Reading the cost from the code You can predict the allocation without a profiler by asking three questions of each lambda in a hot method: 1. **Does it use a local or parameter?** Then a closure object exists for that variable's scope, created every time the scope is entered. 2. **Does it use `this`, directly or through a field, property or instance method?** Then a new delegate is created each time the lambda expression is evaluated. 3. **Does it use nothing from its surroundings?** Then the compiler reuses one cached delegate. A method group passed directly, such as `orders.Exists(IsLarge)` with an instance method, also creates a new delegate each time; converting a method group to a delegate is covered with delegate types. ## Deciding whether it matters - Measure first. A 96-byte allocation per request rarely matters in a typical web handler; in a per-frame game loop or a tight parsing loop it adds steady garbage-collector pressure. - Prefer an ordinary `foreach` loop on the hottest paths; it needs no delegate at all. - Use `static` on lambdas in hot code as a guard, so reviewers do not have to spot captures by eye. - Allocation profiling and benchmarking tools are covered with .NET performance work; the garbage collector's generations are covered with the runtime.

  • In C#, does marking an already non-capturing lambda static make it faster?
    No. Roslyn already caches a non-capturing lambda's delegate in a static field and reuses it, with or without the modifier, and the C# 9 proposal promises nothing about how a static lambda is emitted. The modifier's value is the compile error it raises (CS8820 or CS8821) when someone later adds a capture.
  • In C#, how do you avoid the closure allocation on an early-return path without changing the lambda?
    Move the code that creates the lambda into its own method and call that method only on the path that needs it. The closure object is created on entry to the scope that declares the captured variable, so a separate method confines the allocation to the calls that actually reach the lambda.

  • Says a lambda costs nothing because the compiler always caches delegates.
  • Believes static lambdas are guaranteed to compile to static methods.
  • Claims the closure object is created only when the lambda line runs.
  • Thinks a static lambda cannot use static fields or constants.
  • Rewrites every lambda as static without measuring whether it matters.