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

前端 未结 3 580
鱼传尺愫
鱼传尺愫 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 00:56

    ILSpy decompiles thus:

        public override int Compare(T x, T y)
        {
            if (x != null)
            {
                if (y != null)
                {
                    return x.CompareTo(y);
                }
                return 1;
            }
            else
            {
                if (y != null)
                {
                    return -1;
                }
                return 0;
            }
        }
    

    The null checks will always evaluate as true for a value type, so they will be optimized away; the end result will be

    public override int Compare(T x, T y)
    {
        return x.CompareTo(y);
    }
    

提交回复
热议问题