Enumerating IEnumerable<T> with foreach causes heap allocations due to boxing of struct enumerators. This deep-dive explains why this happens by examining lowered C# code and IL, then demonstrates an advanced technique using Reflection.Emit and DynamicMethod to create allocation-free enumeration. Benchmarks show significant
Table of contents
Background: when foreach allocatesAvoiding foreach allocation for known return typesAvoiding foreach allocation when you can't reference the return typeSummarySort: