OrderBy().Last() or OrderByDescending().First() performance

前端 未结 6 1978
灰色年华
灰色年华 2020-12-09 14:33

I know that this probably is micro-optimization, but still I wonder if there is any difference in using

var lastObject = myList.OrderBy(item => item.Crea         


        
6条回答
  •  臣服心动
    2020-12-09 15:27

    (my answer is about Linq to Objects, not Linq to Entities)

    I don't think there's a big difference between the two instructions, this is clearly a case of micro-optimization. In both cases, the collection needs to be sorted, which usually means a complexity of O(n log n). But you can easily get the same result with a complexity of O(n), by enumerating the collection and keeping track of the min or max value. Jon Skeet provides an implementation in his MoreLinq project, in the form of a MaxBy extension method:

    var lastObject = myList.MaxBy(item => item.Created);
    

提交回复
热议问题