Why is the following code
Array.Sort(values);
Array.Reverse(values);
much faster at sorting an array in descending order compared to
Array.Sort(values, (a,b)=>(-a.CompareTo(b)));
Code was run in Release mode outside of the debugger.
What is the most efficient way to produce a descending sort for arrays, preferably in a one liner?
That’s a great question. I bet your values array is an array of primitive type!
It’s really the sort that is dominant here, because the complexity of Reverse is O(n), while the sort is O(n logn).
The thing is that when sorting primitive types, .NET actually calls a native function, which is extremely fast – much faster that using a Comparison or Comparator.
The function is called
TrySZSort:and here is how it’s called in the Array class: