Figure: Diagnostic workflow: Measure GC allocations → Simplify required search → Measure equivalent work
Figure: Diagnostic workflow: Measure GC allocations → Simplify required search → Measure equivalent work

Cause and mechanism

LINQ provides ways to filter, sort, and transform arrays or lists. Calling it every frame can repeatedly create result arrays or helper objects. Use the Profiler to check execution time and GC Alloc, the amount of newly allocated managed memory, before changing a hot path. A lambda expression does not necessarily allocate memory on every call.

Check and correct the setup

  1. Profile GC Alloc and call stacks on hardware to locate frequent allocations.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time
  2. For a single minimum, scan once rather than sorting everything. Reserve capacity for reusable result lists.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time
  3. Distinguish local captures, delegates referencing this, and noncapturing lambdas. Cache delegates where appropriate; supported C# versions allow static lambdas to prevent captures.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time

Limits and verification

foreach does not always box. Static lambdas do not remove allocations inside the callback, such as string formatting. Measure the actual change instead of promising a fixed speedup or zero bytes.

A focused diagnostic setup

Isolate the expression with matching input size and invocation count. Keep diagnostic logging allocations out of the comparison.

Test in this order

  1. Use allocation call stacks to distinguish enumeration, result materialization and delegate creation.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time
  2. Compare a single scan for one minimum against full sorting; define capacity and clearing for reusable result lists.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time
  3. Repeat after warmup in the same Player, checking both CPU time and allocations.
    GC.Alloc ≠ GC time
    GC.Alloc ≠ GC time

Interpret the result

Removing ToArray can still leave repeated deferred enumeration. Evaluate required traversal count and result lifetime, not allocation alone.

Related explanations

References