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

前端 未结 6 1967
灰色年华
灰色年华 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:13

    just my two cents: since OrderBy or OrderByDescending have to iterate over all the objects anyway, there should be no difference. however, if it were me i would probably just loop through all the items in a foreach with a compare to hold the highest comparing item, which would be an O(n) search instead of whatever order of magnitude the sorting is.

    0 讨论(0)
  • 2020-12-09 15:23

    In both cases it depends somewhat on your underlying collections. If you have knowledge up front about how the collections look before the order and select you could choose one over the other. For example, if you know the list is usually in an ascending (or mostly ascending) sorted order you could prefer the first choice. Or if you know you have indexes on the SQL tables that are sorted ascending. Although the SQL optimizer can probably deal with that anyway.

    In a general case they are equivalent statements. You were right when you said it's micro-optimization.

    0 讨论(0)
  • 2020-12-09 15:27

    Assuming that both ways of sorting take equal time (and that's a big 'if'), then the first method would have the extra cost of doing a .Last(), potentially requiring a full enumeration.

    And that argument probably holds even stronger for an SQL oriented LINQ.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-09 15:27

    I'm sorry this doesn't directly answer your question, but...

    Why not do a better optimization and use Jon Skeet's implementations of MaxBy or MinBy?

    That will be O(n) as opposed to O(n log n) in both of the alternatives you presented.

    0 讨论(0)
  • 2020-12-09 15:30

    Assuming OrderBy and OrderByDescending averages the same performance, taking the first element would permorm better than last when the number of elements is large.

    0 讨论(0)
提交回复
热议问题