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

放肆的年华 提交于 2019-12-04 00:14:44

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).

Stajek

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.

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);
    }
sgmoore

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!