下面的代码正在检查执行相同解决方案的三种不同方法的性能。
public static void Main(string[] args)
{
// for loop
{
Stopwatch sw = Stopwatch.StartNew();
int accumulator = 0;
for (int i = 1; i <= 100000000; ++i)
{
accumulator += i;
}
sw.Stop();
Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, accumulator);
}
//Enumerable.Range
{
Stopwatch sw = Stopwatch.StartNew();
var ret = Enumerable.Range(1, 100000000).Aggregate(0, (accumulator, n) => accumulator + n);
sw.Stop();
Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, ret);
}
//self-made IEnumerable<int>
{
Stopwatch sw = Stopwatch.StartNew();
var ret = GetIntRange(1, 100000000).Aggregate(0, (accumulator, n) => accumulator + n);
sw.Stop();
Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, ret);
}
}
private static IEnumerable<int> GetIntRange(int start, int count)
{
int end = start + count;
for (int i = start; i < end; ++i)
{
yield return i;
}
}
}
结果是:
time = 306; result = 987459712
time = 1301; result = 987459712
time = 2860; result = 987459712
“for 循环”比其他两个解决方案更快并不奇怪,因为 Enumerable.Aggregate 需要更多的方法调用。然而,让我感到惊讶的是,“Enumerable.Range”比“自制的 IEnumerable”要快。我认为 Enumerable.Range 会比简单的 GetIntRange 方法有更多的开销。
可能的原因是什么?