Memory allocation when using foreach loops in C#

前端 未结 4 442
暖寄归人
暖寄归人 2021-02-03 23:52

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 collecti

4条回答
  •  粉色の甜心
    2021-02-04 00:32

    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.

提交回复
热议问题