• Frugal Cafe
  • Posts
  • FC45: Replacing Linq.Enumerable.OrderBy

FC45: Replacing Linq.Enumerable.OrderBy

In-place sorting is better

Over the years, I’ve been reducing usage of LINQ.Enumerable extension methods. The last one was OrderBy/OrderByDescending.

Now let’s replace them for list first, using in-place sorting. Here is the implementation for no delegate version:

For descending order sorting, it’s best to allocate IComparer object to reuse allocation.

Here is the implementation when selector delegate is needed:

Comparer implementation:

Compare with Linq.Enumerable implementation:

Test results:

60% reduction, even more if you already have the list.

InplaceOrderByDescending with selector is 6% slower. The reason is that selector is called 2 N Ln(N) times in our code, but only N times in Linq implementation because it allocates and populates key array first.

When no delegate is used, InplaceOrderByDescending is 27.8% faster.