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!
c# - FirstOrDefault is signicantly faster than SingleOrDefault while viewing ANTS profiler - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
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.
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.
Find() runs almost as twice as faster, hoping . Net team will not mark it Obsolete in the future. Try timing Find() before FirstOrDefault .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With