正如杰森所说,你的代码相当于:
Enumerable.Range(0, 10).Where(n => n % 2 == 0);
请注意,lambda 将被转换为对每个元素进行的函数调用。这可能是开销的最大部分。我做了一个测试,这表明 LINQ 在这个确切的任务上慢了大约 3 倍(mono gmcs 版本 1.2.6.0)
10000000 次循环代表的时间:00:00:17.6852560
10000000 次 LINQ 代表的时间:00:00:59.0574430
1000000 次循环代表的时间:00:00:01.7671640
1000000 次 LINQ 代表的时间:00:00:05.8868350
编辑:Gishu 报告说 VS2008 和框架 v3.5 SP1 提供:
1000000 次循环代表的时间:00.3724585
1000000 次 LINQ 代表的时间::00.5119530
LINQ 在那里慢了大约 1.4 倍。
它将 for 循环和列表与 LINQ(以及它在内部使用的任何结构)进行比较。无论哪种方式,它将结果转换为一个数组(必须强制 LINQ 停止“懒惰”)。两个版本重复:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
public class Evens
{
private static readonly int[] numbers = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
private static int MAX_REPS = 1000000;
public static void Main()
{
Stopwatch watch = new Stopwatch();
watch.Start();
for(int reps = 0; reps < MAX_REPS; reps++)
{
List<int> list = new List<int>(); // This could be optimized with a default size, but we'll skip that.
for(int i = 0; i < numbers.Length; i++)
{
int number = numbers[i];
if(number % 2 == 0)
list.Add(number);
}
int[] evensArray = list.ToArray();
}
watch.Stop();
Console.WriteLine("Time for {0} for loop reps: {1}", MAX_REPS, watch.Elapsed);
watch.Reset();
watch.Start();
for(int reps = 0; reps < MAX_REPS; reps++)
{
var evens = from num in numbers where num % 2 == 0 select num;
int[] evensArray = evens.ToArray();
}
watch.Stop();
Console.WriteLine("Time for {0} LINQ reps: {1}", MAX_REPS, watch.Elapsed);
}
}
过去对类似任务的性能测试(例如LINQ vs Loop - A performance test)证实了这一点。