A recent update has caused significant performance loss in my code. By using a profiler I found that the loss was caused by one single line using Linq. I did some testing and found that Linq was much slower than 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);
Output:
Benchmark run time: 653 foreach run time: 3862 Sum run time: 10233
Does this mean we should always avoid using Linq in performance-critical sections?
Update: Fixed the bug that stopwatch is not reset Do each test once before start the stopwatch for JIT Yes this is in release mode, and is without debugging