編輯: 我看起來更接近一點。由Where
擴展方法返回的WhereEnumerableIterator
實際上覆蓋Where
方法,並將謂詞組合爲單個回調。
public override IEnumerable<TSource> Where(Func<TSource, bool> predicate) {
return new Enumerable.WhereEnumerableIterator<TSource>(
this.source,
Enumerable.CombinePredicates<TSource>(this.predicate, predicate));
}
private static Func<TSource, bool> CombinePredicates<TSource>(
Func<TSource, bool> predicate1, Func<TSource, bool> predicate2
) {
return (TSource x) => predicate1(x) && predicate2(x);
}
所以,我在我的機器上看到的速度差異可能應該歸因於別的。
第一個例子將環比
elements
收集一旦找到滿足條件的
item > 3
,並再次找到滿足條件的
item % 2 == 0
項目的項目。
第二個示例將遍歷elements
集合一次,以查找滿足條件item > 3 && item % 2 == 0
的條目。
在提供的示例中,第二個很可能總是比第一個更快,因爲它只循環超過
elements
一次。
下面是一些相當一致的結果我得到我的機器上(.NET 3.5)的例子:
var stopwatch = new System.Diagnostics.Stopwatch();
var elements = Enumerable.Range(1, 100000000);
var results = default(List<int>);
stopwatch.Start();
results = elements.Where(n => n > 3).Where(n => n % 2 == 0).ToList();
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
stopwatch.Reset();
stopwatch.Start();
results = elements.Where(n => n > 3 && n % 2 == 0).ToList();
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.WriteLine("Done");
Console.ReadLine();
結果:
00:00:03.0932811
00:00:02.3854886
Done
編輯:
@Rawling是正確的,因爲我的解釋僅適用於在POCO對象集合上使用的LINQ。當用作LINQ到SQL,NHibernate,EF等的接口時,您的結果將更依賴於實現。
來源
2012-12-05 14:18:02
ken
另請參見[適當的Linq where子句](http://stackoverflow.com/questions/6359980)。 –