IEnumerable的问题:性能最佳? [英] IEnumerable question: Best performance?
问题描述
快速问题:
哪一个更快?
foreach (Object obj in Collection)
{
if(obj.Mandatory){ ... }
}
或
foreach (Object obj in Collection.FindAll(o => o.Mandatory))
{
...
}
<
and if you know a faster suggestion, i'd be pleased to know.
谢谢
推荐答案
以下测试代码打印系统节拍(1滴= 100纳秒),用于迭代1000万个对象。
The following test code prints the system ticks (1 tick = 100 nanoseconds) for iterating through 10 million objects. The FindAll is slowest and the for loop is fastest as expected.
但是,迭代的开销是以纳秒来衡量的,即使在最坏的情况下。如果你在循环中做任何重要的事情(例如,每个项目需要一微秒),那么迭代的速度差异完全不重要。
But the overhead of the iteration is measured in nanoseconds per item even in the worst case. If you're doing anything significant in the loop (e.g. something which takes a microsecond per item), then the speed difference of the iteration is completely insignificant.
所以对于图灵的爱,现在不要禁止foreach在你的编码指南。它没有任何实际的区别,并且LINQ语句肯定更容易阅读。
So for the love of Turing don't forbid foreach in your coding guidelines now. It doesn't make any practical difference, and the LINQ statements sure are easier to read.
public class Test
{
public bool Bool { get; set; }
}
class Program
{
static void Main(string[] args)
{
// fill test list
var list = new List<Test>();
for (int i=0; i<1e7; i++)
{
list.Add(new Test() { Bool = (i % 2 == 0) });
}
// warm-up
int counter = 0;
DateTime start = DateTime.Now;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Bool)
{
counter++;
}
}
// List.FindAll
counter = 0;
start = DateTime.Now;
foreach (var test in list.FindAll(x => x.Bool))
{
counter++;
}
Console.WriteLine(DateTime.Now.Ticks - start.Ticks); // prints 7969158
// IEnumerable.Where
counter = 0;
start = DateTime.Now;
foreach (var test in list.Where(x => x.Bool))
{
counter++;
}
Console.WriteLine(DateTime.Now.Ticks - start.Ticks); // prints 5156514
// for loop
counter = 0;
start = DateTime.Now;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Bool)
{
counter++;
}
}
Console.WriteLine(DateTime.Now.Ticks - start.Ticks); // prints 2968902
}
这篇关于IEnumerable的问题:性能最佳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!