3 ms·
Foreach in C# doesn't always create garbage, FYI. Enumerators can be structs - List<T>'s is, for example. It's certainly possible to write an application that
by kevingadd 14y ago
Foreach in C# doesn't always create garbage, FYI. Enumerators can be structs - List<T>'s is, for example.
It's certainly possible to write an application that doesn't structurally create garbage, but doing so isn't a universal win. Garbage-free coding patterns are more verbose, harder to get right, and often slower than relying on the GC.
The reason a small hitch is better than no hitch is that if your game is running faster than your target framerate, hitches can be small enough to actually hide between frames - and control over when the GC occurs can allow you to reliably hide your GCs there.
- profquail 14y agoStructs can implement IEnumerator<T> as you mentioned, but they need to be boxed before any interface methods they implement can be called. So, foreach in C# does always create at least a tiny bit of garbage -- but in the case above it's likely to be reclaimed very quickly.
- noblethrasher 14y agoNormally value types do need to be boxed before calling interface methods, but C#'s `foreach` statement is special in that the collection expression just needs to conform to the "collection pattern" rather than implement a particular interface (i.e. IEnumerable). An expression conforms to the collection pattern if it has a public `GetEnumerator` method that returns a type that has a public method of type `MoveNext -> bool` and a public method of type `Current -> Type_Of_The_Element`. In other words, `foreach` uses structural typing rather than nominal typing. Incidentally, value types need only generate garbage in a `foreach` statement if they create a disposable `Enumerator`.
- profquail 14y agoInteresting -- I'd read about this once before but forgotten all about it. Good catch!