Memory allocation when using foreach loops in C#

前端 未结 4 449
暖寄归人
暖寄归人 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:23

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

    The enumerator for the List 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.

提交回复
热议问题