Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 707
dougajmcdonald Avatar asked Feb 15 '13 09:02

dougajmcdonald


People also ask

Is FirstOrDefault faster than SingleOrDefault?

c# - FirstOrDefault is signicantly faster than SingleOrDefault while viewing ANTS profiler - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

Is FirstOrDefault slow?

We use Redgate's Performance profiler to find some performance leaks. Our tool uses Linq to objects in several methods. But we have noticed that a FirstOrDefault takes very long on collections with +/- 1000 objects. The profiler also alerts that the query is very slow.

Should I use FirstOrDefault first?

Use First() when you are sure that a query must return a record, and use FirstOrDefault() when you are not sure whether it will return a record or not.

Which is faster find or FirstOrDefault?

Find() runs almost as twice as faster, hoping . Net team will not mark it Obsolete in the future. Try timing Find() before FirstOrDefault .


1 Answers

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.

like image 181
2 revs Avatar answered Oct 21 '22 22:10

2 revs