Why is List<>.OrderBy LINQ faster than IComparable+List<>.Sort in Debug mode?

前端 未结 4 2186
情歌与酒
情歌与酒 2021-02-19 11:30

I was interested in whether it would be faster to sort my classes using LINQ, or by implementing the IComparable interface and List.Sort. I was quite surprised when the LINQ cod

相关标签:
4条回答
  • 2021-02-19 11:57

    Sort uses unoptimized quicksort, which has a n*n complexity in its worst case. I don't know what orderby uses but I know it doesn't use the same method since it's a stable sort, unlike array.sort.

    0 讨论(0)
  • 2021-02-19 12:03

    This could it be the overhead of calling the method CompareTo which would be replaced with an inline when compile and run in release mode.

    0 讨论(0)
  • 2021-02-19 12:09

    If you make sure everything is JITed before starting the measure, you might get different results (I also recommend using the Stopwatch class to measure time):

    var ll = ts2.ToList();
    ll.Sort();
    ll.OrderBy(item => item.Age).ToList();
    

    According to my measurements (after adding the above code), IComparable is always faster (even in debug).

    0 讨论(0)
  • 2021-02-19 12:12

    For me, I will use Linq with IComparable(when this is the most or only way to sort). In this case, item is a TestSort: IComparable<TestSort>

    var sorted = ll.OrderBy(item => item); // This automatically used age to compare, as it's defined in CompareTo
    

    ll can be any IEnumerable: List, Array, etc.

    Also in CompareTo you can have multiple way to compare... for instance, you can do something like this:

      public int CompareTo(TestSort other) {
            return this.age != other.age ? this.age.CompareTo(other.age) : this.dateOfBirth.CompareTo(other.dateOfBirth);
        }
    
    0 讨论(0)
提交回复
热议问题