Visual Studio gives me the warning "Warning: Possible multiple enumerations" on an IEnumerable
. And then I add ToList()
to it. But I started to wonder why it's a bad practice.
So why is it bad to enumerate multiple times?
Visual Studio gives me the warning "Warning: Possible multiple enumerations" on an IEnumerable
. And then I add ToList()
to it. But I started to wonder why it's a bad practice.
So why is it bad to enumerate multiple times?
“Possible multiple enumeration of IEnumerable“ is a resharper warning. If you enumerate an enumerable more than once, ReSharper will detect this and warn you about it. Although this warning may seem pointless at first, there are two good reasons to pay attention to it:
Enumerating an enumerable can be very expensive. For example, an enumerable might be backed by a database. Re-enumerating may force you to wait another network round trip. You don’t want to pay that cost twice.
Performance problems caused by multiple enumerations compound on themselves.
Please check out this article to get more info about this warning : http://twistedoakstudios.com/blog/Post7694_achieving-exponential-slowdown-by-enumerating-twice
You're essentially looping over the collection twice in your code, which is why you're getting that ReSharper warning.
When using an IEnumerable
returned by a database call, for example, this means getting the data twice, slowing down your application & resulting in unnecessary database load. Why get the data twice?
If using an enumerable in memory, enumerating multiple times over the collection may also be very costly depending on the size of the collection.
Using .ToList()
resolves the error because it forces the enumeration at the point of variable initialization by converting the IEnumerable
to a list (you can also force this by casting the IEnumerable
to an array using ToArray
).
The data inside IEnumerable
collections may also change between enumerations so it's best to force enumeration at the point where you need the data to stay put (the items in the enumerable might be different each time you loop over them).
By JetBrains themselves: Code Inspection: Possible multiple enumeration of IEnumerable
Enumeration of items in an IEnumerable may be costly depending on the implementation type. Enumerating several times over a List in memory does not make much difference. If the IEnumerable is a database selector it may be faster to iterate over it once using toList()
and then iterate over the List