3 ms·
Why is LINQ allocating memory in the first place?
by ImHereToVote 1y ago
Why is LINQ allocating memory in the first place?
- debugnik 1y agoLINQ methods build up a chain of IEnumerable/IQueryable objects, which then build up chains of IEnumerator objects each time you iterate. These types are all .NET interfaces, which are reference types, so they're allocated on the heap. .NET's escape analysis can sometimes move reference types to the stack, but this feature is currently very limited and didn't even exist until .NET 9. ZLinq uses generic structs to prevent these allocations at the expense of some really verbose intermediate types.
- ImHereToVote 1y agoThanks.
- oaiey 1y agoInternal iterators, expression trees, etc. Many LINQ variants (depends on the data source) also do not execute the chain step by step but building first an expression tree and then translating that into native query syntax (e.g. SQL)