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?
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.
Yes. ToList()
would create another list that would need to be garbage collected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With