【发布时间】:2021-03-15 18:05:53
【问题描述】:
问题:为什么Sum()的执行时间比foreach()在以下场景中的执行时间要长?
public void TestMethod4()
{
List<int> numbers = new List<int>();
for (int i = 0; i < 1000000000; i++)
{
numbers.Add(i);
}
Stopwatch sw = Stopwatch.StartNew();
long totalCount = numbers.Sum(num => true ? 1 : 0); // simulating a dummy true condition
sw.Stop();
Console.WriteLine("Time taken Sum() : {0}ms", sw.Elapsed.TotalMilliseconds);
sw = Stopwatch.StartNew();
totalCount = 0;
foreach (var num in numbers)
{
totalCount += true ? 1 : 0; // simulating a dummy true condition
}
sw.Stop();
Console.WriteLine("Time taken foreach() : {0}ms", sw.Elapsed.TotalMilliseconds);
}
示例运行1
Time taken Sum() : 21443.8093ms
Time taken foreach() : 4251.9795ms
【问题讨论】:
-
你错误地使用了
new Random。 -
这是调试版本还是发布版本?你的程序怎么不会因为被零除而崩溃?
-
@Dai,Sum函数中不是除法而是加0。
-
“我发现 Sum() 与 foreach 相比实际上要慢一些”——为什么会让人感到意外?
-
使用 Benchmark dotnet 对代码进行性能分析。 benchmarkdotnet.org/articles/overview.html
标签: c# performance foreach sum