Fan*_*Fan -7 c# linq performance foreach
最近的更新导致我的代码中出现严重的性能损失.通过使用剖析器,我发现损失是由使用Linq的一条线引起的.我做了一些测试,发现Linq慢得多foreach.
List<int> numbers = new List<int>();
for (int i = 0; i < 1000; ++i)
numbers.Add(i);
var stopWatch = new Stopwatch();
{
int total = 0;
for (int i = 0; i < 1000; ++i)
total += i;
}
stopWatch.Start();
for (int j = 0; j < 1000000; ++j)
{
int total = 0;
for (int i = 0; i < 1000; ++i)
total += i;
}
stopWatch.Stop();
Console.WriteLine("Benchmark run time: {0}", stopWatch.ElapsedMilliseconds);
{
int total = 0;
foreach (int i in numbers)
total += i;
}
stopWatch.Restart();
for (int j = 0; j < 1000000; ++j)
{
int total = 0;
foreach (int i in numbers)
total += i;
}
stopWatch.Stop();
Console.WriteLine("foreach run time: {0}", stopWatch.ElapsedMilliseconds);
{
int total = 0;
total += numbers.Sum();
}
stopWatch.Restart();
for (int j = 0; j < 1000000; ++j)
{
int total = 0;
total += numbers.Sum();
}
stopWatch.Stop();
Console.WriteLine("Sum run time: {0}", stopWatch.ElapsedMilliseconds);
Run Code Online (Sandbox Code Playgroud)
输出:
基准运行时间:653运行时间:3862运行时间:10233
这是否意味着我们应该始终避免在性能关键部分使用Linq?
更新:修复秒表未重置的错误在启动JIT秒表之前进行一次测试是的,这是处于发布模式,没有调试
stopWatch.Reset()再次启动之前打电话.否则你的性能测试毫无价值 - 你总结了所有的结果.
您是否在Visual Studio之外的Release版本上运行测试?
是的,LINQ没有for循环那么快.但它更易读,写得更快.