我假设使用相同代码体的lambda函数
、委托
和匿名函数
的速度是相同的,但是运行下面这个简单的程序后:
static void Main(string[] args)
{
List<int> items = new List<int>();
Random random = new Random();
for (int i = 0; i < 10000000; i++)
{
items.Add(random.Next());
}
Stopwatch watch;
IEnumerable<int> result;
Func<int, bool> @delegate = delegate(int i)
{
return i < 500;
};
watch = Stopwatch.StartNew();
result = items.Where(@delegate);
watch.Stop();
Console.WriteLine("Delegate: {0}", watch.Elapsed.TotalMilliseconds);
Func<int, bool> lambda = i => i < 500;
watch = Stopwatch.StartNew();
result = items.Where(lambda);
watch.Stop();
Console.WriteLine("Lambda: {0}", watch.Elapsed.TotalMilliseconds);
watch = Stopwatch.StartNew();
result = items.Where(i => i < 500);
watch.Stop();
Console.WriteLine("Inline: {0}", watch.Elapsed.TotalMilliseconds);
Console.ReadLine();
}
我得到:
委托:4.2948毫秒
lambda表达式:0.0019毫秒
匿名方法:0.0034毫秒
虽然微不足道,但为什么这三种 - 表面上相同的 - 方法运行速度不同?在幕后发生了什么?
更新:
根据评论中的建议,以下代码通过调用ToList()
来“强制”使用Where
。此外,添加了一个循环以提供更多的运行数据:
while (true)
{
List<int> items = new List<int>();
Random random = new Random();
for (int i = 0; i < 10000000; i++)
{
items.Add(random.Next());
}
Stopwatch watch;
IEnumerable<int> result;
Func<int, bool> @delegate = delegate(int i)
{
return i < 500;
};
watch = Stopwatch.StartNew();
result = items.Where(@delegate).ToList();
watch.Stop();
Console.WriteLine("Delegate: {0}", watch.Elapsed.TotalMilliseconds);
Func<int, bool> lambda = i => i < 500;
watch = Stopwatch.StartNew();
result = items.Where(lambda).ToList();
watch.Stop();
Console.WriteLine("Lambda: {0}", watch.Elapsed.TotalMilliseconds);
watch = Stopwatch.StartNew();
result = items.Where(i => i < 500).ToList();
watch.Stop();
Console.WriteLine("Inline: {0}", watch.Elapsed.TotalMilliseconds);
Console.WriteLine(new string('-', 12));
}
以上代码每个函数的执行时间约为120毫秒。
@
符号有什么作用?(@delegate) - Igby Largeman