Secret ingredients to quality software

SSW Foursquare

Do you avoid materializing an IEnumerable?

Last updated by Bryden Oliver on 22 Dec 2021 05:27 am (5 months ago) See History

This is the golden rule of LINQ. You generally have no idea how big the IEnumerable might be, so where possible just iterate through, don't force it into an array or list before doing that.

The primary reason for this is that your input stream might not fit into RAM, and you will cause unnecessary object creation and garbage collection which will also consume a lot of CPU on top of eating memory for breakfast.

foreach(var product in products.ToList())
{
	// Do something
} 

Figure: Bad example - This creates a list with all of the products in RAM before iterating over them. This can very easily cause an OutOfMemoryException.

foreach(var product in products)
{
    	// Do something
}

Figure: Good example - Doesn't force the data to be read into memory before iterating. This will behave nicely even for an infinite enumerator.

Don't materialize an IEnumerable, just iterate it. ie don't ToList or ToArray it until it's been filtered. Do not assume that the input stream fits in RAM.

Bryden OliverBryden Oliver

We open source. Powered by GitHub