33

I know the basics on how foreach loops work in C# (How do foreach loops work in C#)

I am wondering whether using foreach allocates memory that may cause garbage collections? (for all built in System types).

For example, using Reflector on the System.Collections.Generic.List<T> class, here's the implementation of GetEnumerator:

public Enumerator<T> GetEnumerator()
{
    return new Enumerator<T>((List<T>) this);
}

On every usage this allocates a new Enumerator (and more garbage).

Do all types do this? If so, why? (can't a single Enumerator be reused?)

6
  • 2
    a) This is an implementation detail. Those are irrelevant. b) The GC exists. Commented Aug 31, 2013 at 20:49
  • 1
    I guess, the main problem with single Enumerator would be thread safety.
    – volpav
    Commented Aug 31, 2013 at 20:50
  • 2
    This is not limited to foreach(). The whole idea of having a GC is that small, short lived objects are very cheap. We 'waste' them all the time, as in text = text.ToLower();. Don't worry about it. Most re-use schemes turn out more costly. Commented Aug 31, 2013 at 20:59
  • 31
    Anyone who arrives at this page is probably here for a good reason. There are definitely times when every single allocation is important and should be avoided if possible. ("Don't worry about it" may be true 99% of the time, but when it matters it can matter a lot.)
    – yoyo
    Commented Dec 21, 2016 at 18:46
  • 16
    The anti-perf mindset of many speakers of my favorite language, C#, and the constant jabbing from them, a very large group, at the mere hint of someone caring about a low-level perf concern (as you can see in the first comment above), have in the past been detrimental enough to consider if this is the right language for those of us who do care. Such mentalities contributed to a decade plus of keeping C# / .NET from focusing on being lean and mean. I'm so glad that mentality has now been replaced with netcore, I just wish it would work through the ranks quicker. Commented Jul 27, 2018 at 0:50

4 Answers 4

80

Foreach can cause allocations, but at least in newer versions .NET and Mono, it doesn't if you're dealing with the concrete System.Collections.Generic types or arrays. Older versions of these compilers (such as the version of Mono used by Unity3D until 5.5) always generate allocations.

The C# compiler uses duck typing to look for a GetEnumerator() method and uses that if possible. Most GetEnumerator() methods on System.Collection.Generic types have GetEnumerator() methods that return structs, and arrays are handled specially. If your GetEnumerator() method doesn't allocate, you can usually avoid allocations.

However, you will always get an allocation if you are dealing with one of the interfaces IEnumerable, IEnumerable<T>, IList or IList<T>. Even if your implementing class returns a struct, the struct will be boxed and cast to IEnumerator or IEnumerator<T>, which requires an allocation.


NOTE: Since Unity 5.5 updated to C# 6, I know of no current compiler release that still has this second allocation.

There's a second allocation that is a little more complicated to understand. Take this foreach loop:

List<int> valueList = new List<int>() { 1, 2 };
foreach (int value in valueList) {
    // do something with value
}

Up until C# 5.0, it expands to something like this (with certain small differences):

List<int>.Enumerator enumerator = valueList.GetEnumerator();
try {
    while (enumerator.MoveNext()) {
        int value = enumerator.Current;
        // do something with value
    }
}
finally {
    IDisposable disposable = enumerator as System.IDisposable;
    if (disposable != null) disposable.Dispose();
}

While List<int>.Enumerator is a struct, and doesn't need to be allocated on the heap, the cast enumerator as System.IDisposable boxes the struct, which is an allocation. The spec changed with C# 5.0, forbidding the allocation, but .NET broke the spec and optimized the allocation away earlier.

These allocations are extremely minor. Note that an allocation is very different from a memory leak, and with the garbage collection, you generally don't have to worry about it. However, there are some scenarios when you do care about even these allocations. I do Unity3D work and until 5.5, we couldn't have any allocations in operations that happen every game frame because when the garbage collector runs, you get a noticeable lurch.

Note that foreach loops on arrays are handled specially and don't have to call Dispose. So as far as I can tell, foreach has never allocated when looping over arrays.

6
  • 18
    Welcome to SO, and congrats for such a good quality first answer. It's uncommon enough to be pointed out. Commented Sep 30, 2014 at 0:00
  • Why you said that TestHash doesn't allocate, if in IL listing you can clearly see the same cast to IDisposable as in TestIList? Or did you mean that there is no allocation before the loop, but still there is one after? Could you please clarify? Commented Jan 27, 2015 at 20:44
  • Maybe the ildasm confuses the issue now. When I first answered the question, I didn't know the whole story about the IDisposable allocations. The ildasm just shows modern Visual Studio, which no longer allocates by casting to IDisposable. If it were there, you'd see a box instruction. Instead the allocation on the IList is buried in the GetEnumerator call because it has to box its return value to IEnumerator<T>.
    – hangar
    Commented Jan 28, 2015 at 21:46
  • More readable verison of the text linked here by "broke the spec": ericlippert.com/2011/03/14/to-box-or-not-to-box Commented Aug 5, 2020 at 11:33
  • A couple of years ago I had to replace all the foreach loops in my game with regular for loops after discovering how much garbage was being generated. Good to know, thank you.
    – Trap
    Commented Oct 8, 2021 at 11:16
2

No, enumerating a list doesn't cause garbage collections.

The enumerator for the List<T> class doesn't allocate memory from the heap. It's a structure, not a class, so the constructor doesn't allocate an object, it just returns a value. The foreach code would keep that value on the stack, not on the heap.

Enumerators for other collections may be classes though, which would allocate an object on the heap. You would need to check the type of the enumerator for each case to be certain.

2
  • 2
    Not sure what was the situation in 2013, but just in case you stumble upon this in now as I did, this is not correct. At the moment, IEnumerable<T>::GetEnumerator() returns an interface, which boxes the enumerator if it is a struct, thus forcing a heap allocation. See stackoverflow.com/a/14289283/320103 for a nice example
    – Michael
    Commented Apr 23, 2022 at 17:45
  • I have a List<InterfaceT> where T is a class that implements InterfaceT. The List is being stored as an IEnumerable<InterfaceT>. Whenever I foreach over the list it allocates when calling GetEnumerator(). Could this be due to boxing?
    – Nic Foster
    Commented Aug 18, 2023 at 22:53
-1

Because an enumerator keeps hold of the current item. It's like a cursor compared to databases. If multiple threads would access the same enumerator, you would lose control of the sequence. And you would have to reset it to the first item every time a foreach consults it.

-1

As mentioned in comments, this generally should not be an issue you need worry about, as that is the point of Garbage Collection. That said, my understanding is that yes, each foreach loop will generate a new Enumerator object, which will eventually be garbage collected. To see why, look at the documentation for the interface here. As you can see, there is a function call which requests the next object. The ability to do this implies the enumerator has state, and must know which one is next. As to why this is necessary, image you're causing an interaction between every permutation of collection Items:

foreach(var outerItem in Items)
{
   foreach(var innterItem in Items)
   {
      // do something
   }
}

Here you have two enumerators on the same collection at the same time. Clearly a shared location would not accomplish your goal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.