Thursday, 15 July 2010

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



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

this question has reply here:

orderby().last() or orderbydescending().first() performance 6 answers

i had linq question wondered if knew reply to.

normally if wanted find record ordered particular field, such 'latest added person' i'd write like:

mycollection.orderbydescending(x => x.addeddate).firstordefault();

recently picked work dev in team prefers write:

mycollection.orderby(x => x.addeddate).lastordefault();

so question this, ordering descending , selecting first, quicker or slowing ordering other direction , selecting last?

my thoughts first quicker it's not needing iterate on collection 'as far' when returning object, more hunch else!

if you're using linq-to-objects, first 1 marginally faster. 2 sorts each take same amount of time*, you're right in thinking firstordefault faster lastordefault. however, difference negligible compared time sort takes.

(note doing whole sort take top item far more inefficient using last on first; consider implementing morelinq's maxby function item want in o(n), rather o(n log n), time.)

if you're using linq-to-something else (sql, entities), it'll create no difference @ all.

* in general; rb points out might not case if info ordered extent.

c# performance linq

No comments:

Post a Comment