The last time we analyzed the implementation of the Array.sort<t> method and learned that the class library would use high-performance sorting methods for some special cases--int arrays are such an example, so the performance of the test results is particularly high. However, from the data, even under normal circumstances,,array.sort<t> performance is higher than the LINQ sort. But also a friend from the test to draw the conclusion is the opposite, this is why? So now, let's analyze how the LINQ sort is implemented, and hopefully this will give you a sense of the difference in performance.
Unfortunately, LINQ-sorted code in the System.Core.dll assembly, Microsoft did not release this part of the source code, we have to use the. NET reflector to find out.
Definition, use, and extension of LINQ sort interfaces
The so-called LINQ ordering is the use of several extension methods defined in the System.Linq.Enumerable class, which are:
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey> (
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer);
public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer);
For ease of use, I tend to add additional interfaces, such as:
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey> (
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, bool decending)
{
return decending ?
source.OrderByDescending(keySelector) :
source.OrderBy(keySelector);
}
When used, you can use a Boolean value to indicate the direction of the sort (ascending or descending) without having to "manually" select one from the two methods. In addition, it's a bit of a hassle to construct a icomparer<tkey> type, so I went on to extend an interface that uses a delegate object as a "comparer", as Array.sort<t> has done:
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey> (
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Comparison<TKey> compare, bool decending)
{
return decending ?
source.OrderByDescending(keySelector, new FunctorComparer<TKey>(compare)) :
source.OrderBy(keySelector, new FunctorComparer<TKey>(compare));
}