I was spending my free time comparing built-in sorting algorithms in various libraries and languages and whe I hit C# and .NET I stumbled across a quite interesting and yet unknown to me "quirk". Here's the fist program I ran:
class Program { static void Main(string[] args) { var a = new int[1000000]; var r = new Random(); var t = DateTime.Now; for (int i = 0; i < 1000000; i++) { a[i] = r.Next(); } Console.WriteLine(DateTime.Now - t); t = DateTime.Now; Array.Sort(a); Console.WriteLine(DateTime.Now - t); Console.ReadKey(); } }
and I got an average result of 11 ms for filling the array and 77 ms for sorting.
Then I tried this code:
class Program { static void Main(string[] args) { var a = new int[1000000]; var r = new Random(); var t = DateTime.Now; Array.ForEach(a, x => x = r.Next()); Console.WriteLine(DateTime.Now - t); t = DateTime.Now; Array.Sort(a); Console.WriteLine(DateTime.Now - t); Console.ReadKey(); } }
and to my surprise the average times were 14 ms and 36 ms.
How can this be explained?