foreach - an interesting beast; many people mistakenly believe that it is tied to IEnumerable[<T>] / IEnumerator[<T>] , but this is simply not so. Therefore, it makes no sense to say:
Each iteration of each foreach loop generates 24 bytes of garbage memory.
In particular, it depends on what you are looping. For example, many types have custom iterators - List<T> , for example, has a struct based iterator. Null objects are highlighted below:
// assume someList is a List<SomeType> foreach(var item in someList) { // do something with item }
However, this object selects objects:
IList<SomeType> data = someList; foreach(var item in data) {
Which looks identical, but not - by changing the foreach to iterate over IList<SomeType> (which does not have a custom GetEnumerator() method, but which implements IEnumerable<SomeType> ), we force it to use the IEnumerable[<T>] / IEnumerator<T> API IEnumerator<T> , which is necessarily associated with the object.
Edit caveat: note I assume here that unity can preserve the semantics of the value of a custom iterator type; if unity is forced to erect structures to objects, then, frankly, all bets are off.
Be that as it may, I would be glad to say “be sure to use for and the index in this case” if each distribution matters, but in principle: the expression on the clothes on foreach useless and misleading.
Marc gravell
source share