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