C# FirstOrDefault/First 和 OrderByDescending 是否比 LastOrDefault/Last 和 OrderBy 快?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14891532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is FirstOrDefault/First and OrderByDescending, quicker than LastOrDefault/Last and OrderBy?
提问by dougajmcdonald
I had a LINQ question I wondered if anyone knew the answer to.
我有一个 LINQ 问题,我想知道是否有人知道答案。
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:
最近我从团队中另一个喜欢写作的 Dev 那里得到了一些工作:
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!
我的想法是,第一个会更快,因为它不需要在返回对象时“尽可能”地迭代集合,但这更像是一种预感!
采纳答案by Rawling
If you're using LINQ-to-Objects, the first one will be marginallyfaster. 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.
如果您使用 LINQ-to-Objects,第一个会稍微快一点。这两种类型都需要相同的时间*,但您认为这FirstOrDefault
比LastOrDefault
. 但是,与排序所需的时间相比,差异可以忽略不计。
(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.)
(请注意,做一整套只取最上面的项目比使用Last
over效率低得多First
;考虑实现类似 MoreLINQ 的MaxBy
函数来获取你想要的项目O(n)
,而不是O(n log n)
时间。)
If you're using LINQ-to-something else (SQL, Entities), it'll probably make no difference at all.
如果您使用 LINQ 到其他东西(SQL、实体),它可能根本没有区别。
* in general; as RB points out this might not be the case if the data is already ordered to some extent.
* 一般来说; 正如 RB 指出的那样,如果数据已经在某种程度上进行了排序,则情况可能并非如此。