开发者

LINQ orderby vs IComparer

开发者 https://www.devze.com 2023-01-09 12:17 出处:网络
I would like to know what is better to use. IComparer class and Compare method for sort or LINQ orderby on List. Bo开发者_JAVA百科th works fine but which one is better for large lists.I would choose

I would like to know what is better to use.

IComparer class and Compare method for sort or LINQ orderby on List. Bo开发者_JAVA百科th works fine but which one is better for large lists.


I would choose LINQ for two reasons.

  • LINQ queries are generally shorter and easier to read.
  • If you really do have a large number of elements, Linq also gives you the ability to scale out to multiple CPU cores by using PLinq, which might help you out significantly.

I would expect performance to be roughly similar for a single-threaded implementation, if you consider that the lambda expression in your OrderBy clause compiles to a function -- which is pretty much all you get by implementing IComparer anyway.

That being said, you might get more of a performance boost by changing your sort algorithm to be tailored to how your data is already sorted, rather than by changing your comparison method. But I'd be willing to bet my coffee this morning that OrderBy in your Linq statements uses an implementation of Quicksort, so it's probably pretty decent in the general case already.


I prefer using LINQ by default for all collection-based operations. The advantage here is that I don't have to assume too much on the type of the collection used (OrderBy works on IEnumerable).

If you have an IList<T> anyway, then List.Sort will probably be faster.

Anyhow, I wouldn't worry about it before there is a proven (i.e. measured) performance problem


I think semantically the two are very different, IComparer interface lets you define how your type is sorted naturally, OrderBy gives you a way to sort your objects by some specific key, e.g. given a list of Person objects, for query A sort the list by First Name, for query B sort the list by Age.

LINQ gives you more flexibility, but as OrderBy requires a Func which takes your object type and returns a key to use for sorting, whatever key you return will still need to implement the IComparer interface.

In terms of performance on a large list, depending on what you're doing in the Compare method there are probably very little difference between the two approaches I'd imagine, though it's best to just test it out against your type.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号