LINQ orderby vs IComparer

2019-02-06 06:50发布

I would like to know what is better to use.

IComparer class and Compare method for sort or LINQ orderby on List. Both works fine but which one is better for large lists.

3条回答
手持菜刀,她持情操
2楼-- · 2019-02-06 07:18

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.

查看更多
疯言疯语
3楼-- · 2019-02-06 07:19

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.

查看更多
孤傲高冷的网名
4楼-- · 2019-02-06 07:38

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

查看更多
登录 后发表回答