[英]Why is LastOrDefault(predicate) in LINQ faster than FirstOrDefault(predicate)
[英]Why is LINQ .Where(predicate).First() faster than .First(predicate)?
我正在做一些性能测试,发现LINQ表达式像
result = list.First(f => f.Id == i).Property
比慢
result = list.Where(f => f.Id == i).First().Property
这似乎与直觉相反。 我以为第一个表达式会更快,因为一旦满足谓词,它就可以停止迭代列表,而我以为.Where()
表达式可能会在调用.First()
之前.Where()
迭代整个列表.First()
。 即使后者短路,也不应比直接使用First更快。
下面是两个非常简单的单元测试,它们说明了这一点。 在.Net和Silverlight 4上使用TestWhereAndFirst进行优化编译时,其速度比TestFirstOnly快30%。我试图使谓词返回更多结果,但是性能差异是相同的。
谁能解释为什么.First(fn)
比.Where(fn).First()
慢? 与.Where(fn).Count()
相比,我看到了.Count(fn)
类似的反直观结果。
private const int Range = 50000;
private class Simple
{
public int Id { get; set; }
public int Value { get; set; }
}
[TestMethod()]
public void TestFirstOnly()
{
List<Simple> list = new List<Simple>(Range);
for (int i = Range - 1; i >= 0; --i)
{
list.Add(new Simple { Id = i, Value = 10 });
}
int result = 0;
for (int i = 0; i < Range; ++i)
{
result += list.First(f => f.Id == i).Value;
}
Assert.IsTrue(result > 0);
}
[TestMethod()]
public void TestWhereAndFirst()
{
List<Simple> list = new List<Simple>(Range);
for (int i = Range - 1; i >= 0; --i)
{
list.Add(new Simple { Id = i, Value = 10 });
}
int result = 0;
for (int i = 0; i < Range; ++i)
{
result += list.Where(f => f.Id == i).First().Value;
}
Assert.IsTrue(result > 0);
}
我得到了相同的结果:where + first比first更快。
如乔恩(Jon)所述,Linq使用惰性评估,因此两种方法的性能应该(并且应该)大致相似。
在Reflector中看,First使用一个简单的foreach循环来遍历集合,但是Where中有各种专门针对不同集合类型(数组,列表等)的迭代器。 大概这就是给Where带来小的优势的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.