I iterate through an IEnumerable as the result of a Linq query using (ElementAt,Count) and (foreach). To my surprise, the performance difference is 25-30 fold! Why is that?
IEnumerable<double> result =
... simple Linq query that joins two tables
... returns about 600 items
double total = 0;
// Method 1: iterate with Count and ElementAt
for( int i = 0; i < result.Count(); i++ )
{
total += result.ElementAt(i);
}
// Method 2: iterate with foreach
foreach( double value in result )
{
total += value;
}
The
ElementAt()method is O(n), unless the actual concrete class that theIEnumerablerepresents optimizes it. That means that every time you call it, it has to loop through the entire Enumerable to find the element atn. Not to mention that since you havei < result.Count()in the condition part of yourforloop, it’s gotta loop through the entire enumerable every single time to get that count.The second way, you loop through
resultexactly once.