Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Performance: (ElementAt,Count) vs (foreach)

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;
}
like image 514
Candy Chiu Avatar asked Nov 10 '11 17:11

Candy Chiu


2 Answers

The ElementAt() method is O(n), unless the actual concrete class that the IEnumerable represents optimizes it. That means that every time you call it, it has to loop through the entire Enumerable to find the element at n. Not to mention that since you have i < result.Count() in the condition part of your for loop, it's gotta loop through the entire enumerable every single time to get that count.

The second way, you loop through result exactly once.

like image 76
rossipedia Avatar answered Sep 18 '22 13:09

rossipedia


Because ElementAt is iterating through the IEnumerable every time you call it. IEnumerables are not indexed so ElementAt must be implemented using GetEnumerator().

Why not do

total = result.Sum();
like image 25
Jodrell Avatar answered Sep 21 '22 13:09

Jodrell