Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderBy().Last() or OrderByDescending().First() performance

Tags:

c#

.net

linq

I know that this probably is micro-optimization, but still I wonder if there is any difference in using

var lastObject = myList.OrderBy(item => item.Created).Last(); 

or

var lastObject = myList.OrderByDescending(item => item.Created).First(); 

I am looking for answers for Linq to objects and Linq to Entities.

like image 731
Residuum Avatar asked Jul 13 '11 14:07

Residuum


People also ask

What is difference between OrderBy and ThenBy in Linq?

Generally, ThenBy method is used with the OrderBy method. The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.

How does OrderBy and ThenBy work?

The ThenBy and ThenByDescending extension methods are used for sorting on multiple fields. The OrderBy() method sorts the collection in ascending order based on specified field. Use ThenBy() method after OrderBy to sort the collection on another field in ascending order.

Does OrderBy work on string?

OrderBy" function utilizes the default comparer for a string. That comparer is not necessarily going to return a sort order based on the ASCII code. For a list of all the different string comparers, see the article on MSDN.

What is OrderBy in Linq?

Sorts the elements of a sequence in ascending order according to a key. OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) Sorts the elements of a sequence in ascending order by using a specified comparer.


2 Answers

Assuming that both ways of sorting take equal time (and that's a big 'if'), then the first method would have the extra cost of doing a .Last(), potentially requiring a full enumeration.

And that argument probably holds even stronger for an SQL oriented LINQ.

like image 127
Henk Holterman Avatar answered Sep 23 '22 20:09

Henk Holterman


(my answer is about Linq to Objects, not Linq to Entities)

I don't think there's a big difference between the two instructions, this is clearly a case of micro-optimization. In both cases, the collection needs to be sorted, which usually means a complexity of O(n log n). But you can easily get the same result with a complexity of O(n), by enumerating the collection and keeping track of the min or max value. Jon Skeet provides an implementation in his MoreLinq project, in the form of a MaxBy extension method:

var lastObject = myList.MaxBy(item => item.Created); 
like image 33
Thomas Levesque Avatar answered Sep 19 '22 20:09

Thomas Levesque