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
- Profile GC Alloc and call stacks on hardware to locate frequent allocations.
GC.Alloc ≠ GC time - For a single minimum, scan once rather than sorting everything. Reserve capacity for reusable result lists.
GC.Alloc ≠ GC time - 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
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
- Use allocation call stacks to distinguish enumeration, result materialization and delegate creation.
GC.Alloc ≠ GC time - Compare a single scan for one minimum against full sorting; define capacity and clearing for reusable result lists.
GC.Alloc ≠ GC time - Repeat after warmup in the same Player, checking both CPU time and allocations.
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.