Question

Are there any difference in performance between

List<T>.Sort Method (Comparison<T>)

and

List<T>.Sort Method (IComparer<T>)?

Does exists any structural (software architectural) benefits?

When do you use the compare method instead of compare class and vice versa?

EDIT:

The List<T>.Sort Method (IComparer<T>) is faster. Thanks Jim Mischel!

The performance difference is around 1% on my PC.

It seems that the compare class is the faster one.

Was it helpful?

Solution 2

As I recall, List.Sort(Comparer<T>) instantiates an IComparer<T> and then calls List.Sort(IComparer<T>).

It looks something like this:

class SortComparer<T>: IComparer<T>
{
    private readonly Comparison<T> _compare;
    public SortComparer(Comparison<T> comp)
    {
        _compare = comp;
    }

    public int Compare(T x, T y)
    {
        return _compare(x, y);
    }
}

public Sort(Comparison<T> comp)
{
    Sort(new SortComparer(comp));
}

So they really end up doing the same thing. When I timed this stuff (back in .NET 3.5), Sort(IComparer<T>) was slightly faster because it didn't have to do the extra dereference on every call. But the difference really wasn't big enough to worry about. This is definitely a case of use whatever works best in your code rather than what performs the fastest.

A little more about it, including information about default IComparer implementations: Of Comparison and IComparer

OTHER TIPS

The difference is that the first accepts a method (anonymous or not) and the second accepts an instance of a comparer object. Sometimes it is easier to define complex and customizeable comparer classes rather than write everything inside a single function.

I prefer the first for simple sorting in one dimension and the latter for multidimensional sorting in e.g. data grids.

Using a comparer you can have private members which can often help with caching. This is useful in certain scenarios (again, in complex sorting of a large data set displayed in a grid).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top