Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is garbage created in this foreach loop?

I came across a method to change a list in a foreach loop by converting to a list in itself like this:

foreach (var item in myList.ToList())
{
     //add or remove items from myList
}

(If you attempt to modify myList directly an error is thrown since the enumerator basically locks it)

This works because it's not the original myList that's being modified. My question is, does this method create garbage when the loop is over (namely from the List that's returned from the ToList method? For small loops, would it be preferable to using a for loop to avoid the creation of garbage?

like image 928
Skoder Avatar asked Dec 28 '22 19:12

Skoder


2 Answers

The second list is going to be garbage, there will be garbage for an enumerator that is used in building the second list, and add in the enumerator that the foreach would spawn, which you would have had with or without the second list.

Should you switch to a for? Maybe, if you can point to this region of code being a true performance bottleneck. Otherwise, code for simplicity and maintainability.

like image 198
Anthony Pegram Avatar answered Jan 04 '23 18:01

Anthony Pegram


Yes. ToList() would create another list that would need to be garbage collected.

like image 34
Jacob Avatar answered Jan 04 '23 20:01

Jacob