I've noticed that when sorting an array in .NET using a custom IComparer<T>
, requests are made for comparisons of an item against itself.
Why is this the case? Surely it's a trivial optimization to see if a comparison is about to be made of identical indexes, and assume the result must be zero?
Example code:
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 output (strange comparisons marked):
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 ***