Why is List.Sort using Comparer.Default more than twice as fast as an equivalent custom comparer?

前端 未结 3 584
鱼传尺愫
鱼传尺愫 2021-01-08 00:22

Results

Using a list of 10 million random ints (same seed each time, average of 10 repetitions):

listCopy.Sort(Comparer.Defau

3条回答
  •  花落未央
    2021-01-08 01:16

    The default comparer for Int32 is the CompareTo(int,int) method. Your assumption of the default comparer is incorrect.

    The IComparable interface provides a strongly typed comparison method for ordering members of a generic collection object. Because of this, it is usually not called directly from developer code. Instead, it is called automatically by methods such as List.Sort() and Add.

    http://msdn.microsoft.com/en-us/library/4d7sx9hd.aspx. The IComparable interface mentioned defines the CompareTo method.

    So we should expect your comparer to be about the same speed. So why might it be slower? If we dig down into the Sort method in .Net, we eventually get to this line:

    if ((length > 1) && (((comparer != null) && (comparer != Comparer.Default)) || !TrySZSort(array, null, index, (index + length) - 1)))
    {
        ArraySortHelper.Default.Sort(array, index, length, comparer);
    }
    

    If the comparer equals the default comparer for that type, the Array Sort will try to use an internal optimized sort method. Your comparer is not the default comparer, so it skips that optimized sort.

提交回复
热议问题