Search code examples
c#sortinggeneric-collections

Is there any performance difference between compare method and compare class?


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.


Solution

  • 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