I can sort a list using Sort or OrderBy. Which one is faster? Are both working on same algorithm?
List<Person> persons = new List<Person>();
persons.Add(new Person("P005", "Janson"));
persons.Add(new Person("P002", "Aravind"));
persons.Add(new Person("P007", "Kazhal"));
1.
persons.Sort((p1,p2)=>string.Compare(p1.Name,p2.Name,true));
2.
var query = persons.OrderBy(n => n.Name, new NameComparer());
class NameComparer : IComparer<string>
{
public int Compare(string x,string y)
{
return string.Compare(x, y, true);
}
}
In a nutshell :
List/Array Sort() :
OrderBy/ThenBy() :
x => x.Id
). All keys are extracted first before sorting. This might result in better performance than using Sort() and a custom comparer.Sources: MDSN, reference source and dotnet/coreclr repository (GitHub).
Some of the statements listed above are based on current .NET framework implementation (4.7.2). It might change in the future.
I think it's important to note another difference between
Sort
andOrderBy
:Suppose there exists a
Person.CalculateSalary()
method, which takes a lot of time; possibly more than even the operation of sorting a large list.Compare
Option 2 may have superior performance, because it only calls the
CalculateSalary
method n times, whereas theSort
option might callCalculateSalary
up to 2n log(n) times, depending on the sort algorithm's success.Darin Dimitrov's answer shows that
OrderBy
is slightly faster thanList.Sort
when faced with already-sorted input. I modified his code so it repeatedly sorts the unsorted data, andOrderBy
is in most cases slightly slower.Furthermore, the
OrderBy
test usesToArray
to force enumeration of the Linq enumerator, but that obviously returns a type (Person[]
) which is different from the input type (List<Person>
). I therefore re-ran the test usingToList
rather thanToArray
and got an even bigger difference:The code:
you should calculate the complexity of algorithms used by the methods OrderBy and Sort. QuickSort has a complexity of n (log n) as i remember, where n is the length of the array.
i've searched for orderby's too, but i could not find any information even in msdn library. if you have not any same values and sorting related to only one property, i prefer to use Sort() method; if not than use OrderBy.
I just want to add that orderby is way more useful.
Why?
Because I can do this
Why complicated comparer? Just sort based on a field. Here I am sorting based on TotalBalance.
Very easy
I can't do that with sort. I wonder why. Do fine with orderBy.
As for speed. It's always O(n)
Why not measure it:
On my computer when compiled in Release mode this program prints:
UPDATE:
As suggested by @Stefan here are the results of sorting a big list fewer times:
Prints:
In this scenario it looks like OrderBy performs better.
UPDATE2:
And using random names:
Where:
Yields:
Still OrderBy is faster