runtime: .net 7.0 perf regression with stopwatch
Same code runs about 15% faster in older .net 6.0 than in 7.0 tested on Windows 10 and net 7.0.10 runtime
int[] arrayToSort = new int[1000];
Random random = new Random();
for (int i = 0; i < arrayToSort.Length; i++)
{
arrayToSort[i] = random.Next();
}
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < 500000; i++)
{
Array.Sort(arrayToSort);
}
stopwatch.Stop();
totalElapsedTime += stopwatch.ElapsedMilliseconds;
Console.WriteLine($"Sorting took: {stopwatch.ElapsedMilliseconds} ms");
About this issue
- Original URL
- State: closed
- Created a year ago
- Comments: 17 (8 by maintainers)
Ok, I will close. Feel free to re-open or create new issues if you see other issues with performance. Thanks!
Likely what is happening is that one extra line changes the memory address where the array is allocated slightly and this is what is leading to the performance impact you’re seeing. Try adding two or more
new Stopwatchand you may see performance change yet again.See eg https://github.com/dotnet/BenchmarkDotNet/issues/1513
If you’re interested learning more about the ways today’s microarchtectures can make benchmarking tricky you might consider reading about stabilizer.
I checked your benchmark both with
stopwatch = new Stopwatch();linecommented:
and uncommented:
It seems like there was some problem in .NET 7 (maybe OSR?), but in the latest .NET 8 preview 7 it is fixed