Hacker News new | ask | show | jobs
by kfuse 43 days ago
"IEnumerable should not be forced to return a type-erased = heap allocated IEnumerator instance."

Foreach loops use compile-time duck typing, so if you don't intend to use your enumerable in LINQ then both the enumerable and enumerator don't need to implement any interfaces.

This optimisation covers only one common use case, but that's the way of things in C# land.

2 comments

IEnumerators can also be value types So no heap allocation, just stack.

slightly off topic but a lot of things in .NET actually use compile time duct typing. like how async works To make your own task, you don't add an interface to it. You just implement a single method.

I’m aware. I would consider the fact that LINQ has caveats a failure of language design - it’s so convenient, but you just can’t use it for performance-sensitive stuff.

Meanwhile, iterators in Rust frequently outperform manual loops.

ZLinq exists: https://github.com/Cysharp/ZLinq

    > Zero allocation LINQ with LINQ to Span, LINQ to SIMD, and LINQ to Tree (FileSystem, JSON, GameObject, etc.) for all .NET platforms and Unity, Godot.
Yup, I’m a happy user of it. Writing generic code with these enumerators is extremely verbose, because the language lacks associated types.