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 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.
Because ElementAt
is iterating through the IEnumerable
every time you call it. IEnumerable
s are not indexed so ElementAt
must be implemented using GetEnumerator()
.
Why not do
total = result.Sum();
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