Figure: Diagnostic workflow: Identify captured state → Reuse suitable delegates → Remeasure allocations
Figure: Diagnostic workflow: Identify captured state → Reuse suitable delegates → Remeasure allocations

Cause and mechanism

A lambda expression writes a short function where it is needed. Using an outer local variable can create a capture that stores access to that value, allocating an object or delegate. Locate allocations in the Profiler and distinguish these cases from capture-free lambdas or those referring only to this.

Check and correct the setup

  1. Use Development Build allocation call stacks to distinguish delegate construction, captured-state storage, and allocations inside the callback.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time
  2. Keep reusable delegates at an appropriate lifetime. Unsubscribe from long-lived events to avoid retaining captured objects unnecessarily.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time
  3. Where the C# version supports them, static lambdas prevent unintended capture. Consider APIs accepting explicit state and compare the same number of calls.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time

Limits and verification

A captured variable is not necessarily a snapshot of its value when the delegate was created. Caching a delegate does not remove string or LINQ allocations inside its callback; measure allocation and execution cost separately.

A focused diagnostic setup

Compare a per-frame delegate capturing a local with a reusable version. Temporarily remove allocations inside the callback.

Test in this order

  1. Locate delegate and captured-state allocations in call stacks.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time
  2. Reuse only when lifetimes fit; compare explicit-state APIs where appropriate.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time
  3. Verify event removal and retained targets, then profile the Player again.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time

Interpret the result

Caching does not remove LINQ/string work inside callbacks. Long-lived event subscriptions can retain targets, so inspect lifetime as well as allocation.

Related explanations

References