I noticed that when sorting an array in .NET using a custom IComparer<T> queries are executed to map the element to itself.
Why is this so? Of course, this is a trivial optimization to see if the comparison should consist of identical indices, and to assume that the result should be zero?
Code example:
class Comparer : IComparer<string> { public int Compare(string x, string y) { Console.WriteLine("{0} vs {1}", x, y); return string.Compare(x, y); } } static void Main(string[] args) { var values = new[] {"A", "D", "C", "B", "E"}; Array.Sort(values, new Comparer()); }
With an exit (strange comparisons are noted):
A vs C A vs E C vs E A vs C D vs C C vs E C vs B C vs C *** C vs C *** A vs B A vs B A vs A *** A vs B A vs A *** D vs E D vs E D vs D *** D vs E D vs D ***
source share