Linq性能:(ElementAt,Count)vs(foreach) [英] Linq Performance: (ElementAt,Count) vs (foreach)

查看:184
本文介绍了Linq性能:(ElementAt,Count)vs(foreach)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用(ElementAt,Count)和(foreach)作为Linq查询的结果遍历IEnumerable.令我惊讶的是,性能差异是25到30倍!为什么会这样?

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;
}

推荐答案

ElementAt()方法为O(n),除非IEnumerable表示的实际具体类对其进行优化.这意味着每次调用它时,它都必须遍历整个Enumerable,以在n处找到该元素.更不用说,由于您在for循环的条件部分中有i < result.Count(),因此每次必须遍历整个枚举才能获得该计数.

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.

第二种方法,您只循环遍历result一次.

The second way, you loop through result exactly once.

这篇关于Linq性能:(ElementAt,Count)vs(foreach)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆