Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ orderby vs IComparer

Tags:

c#

linq

icomparer

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.

like image 215
senzacionale Avatar asked Jul 31 '10 14:07

senzacionale


3 Answers

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.

like image 88
Dave Markle Avatar answered Nov 08 '22 14:11

Dave Markle


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

like image 28
jeroenh Avatar answered Nov 08 '22 14:11

jeroenh


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.

like image 2
theburningmonk Avatar answered Nov 08 '22 14:11

theburningmonk