Is FirstOrDefault/First and OrderByDescending, quicker than LastOrDefault/Last and OrderBy?

c#, linq, performance

Solution

If you're using LINQ-to-Objects, the first one will be marginally faster. The two sorts will each take the same amount of time*, but you're right in thinking that `FirstOrDefault` is faster than `LastOrDefault`. However, the difference will be negligible compared to the time the sort takes.

(Note that doing a whole sort to take just the top item is far more inefficient than using `Last` over `First`; consider implementing something like MoreLINQ's `MaxBy` function to get the item you want in `O(n)`, rather than `O(n log n)`, time.)

If you're using LINQ-to-something else (SQL, Entities), it'll probably make no difference at all.

* in general; as RB points out this might not be the case if the data is already ordered to some extent.

Problem

I had a LINQ question I wondered if anyone knew the answer to. Normally if I wanted to find a record ordered by a particular field, such as the 'latest added person' I'd write something like: ``` MyCollection.OrderByDescending(x => x.AddedDate).FirstOrDefault(); ``` Recently I picked up some work from another Dev in the team who prefers to write: ``` MyCollection.OrderBy(x => x.AddedDate).LastOrDefault(); ``` So my question is this, is ordering descending and selecting the first, quicker or slowing than ordering the other direction and selecting last? My thoughts are that first would be quicker as it's not needing to iterate over the collection 'as far' when returning an object, but this is more a hunch than anything else!

Original source

Related problems