- Frugal Cafe
- Posts
- FC46: Beat Linq.Enumerable.OrderBy with delegate
FC46: Beat Linq.Enumerable.OrderBy with delegate
Array.Sort supports a key array
In previous post, we discussed how to replace Linq.Enumerable.OrderBy / OrderByDescending with in-place sorting on lists. One issue is that when delegate is used, our code is slower. The reason behind that is that in Linq implementation there is a key array allocated, so delegates are invoked much less often.
Let’s beat that using key array supported by Array.Sort:
We just need to rent a key array, populate it, and then call Array.Sort with two arrays: key array, plus data array. It’s actually quite easy.
Add this new case to the original perf test:
Updated results:
OpenList.SortDescending is 8% faster than Linq, and allocates 60% less. We have a clear winner.