Repository navigation
Description
Currently, there is no way to sort native or fixed memory (e.g. coming from a pointer) in .NET, this proposal intends to fix that by adding sorting extension methods to Span<T>, but also proposes some different overloads than seen on Array to allow for inlined comparisons via the possibility to use value type comparers.
Proposed API
Add a set of Sort extension methods to Span<T> in SpanExtensions:
public static class SpanExtensions
{
public static void Sort<T>(this Span<T> span);
public static void Sort<T, TComparer>(this Span<T> span, TComparer comparer)
where TComparer : IComparer<T>;
public static void Sort<T>(this Span<T> span, System.Comparison<T> comparison);
public static void Sort<TKey, TValue>(this Span<TKey> keys, Span<TValue> items);
public static void Sort<TKey, TValue, TComparer>(this Span<TKey> keys,
Span<TValue> items, TComparer comparer)
where TComparer : IComparer<TKey>;
public static void Sort<TKey, TValue>(this Span<TKey> keys,
Span<TValue> items, System.Comparison<TKey> comparison);
}Rationale and Usage
Provide a safe yet fast way of sorting of any type of contiguous memory; managed or unmanaged.
Sorting Native Memory
var span = new Span<int>(ptr, length);
span.Sort(); // Sort elements in native memorySorting with Inlineable Comparer
struct ReverseComparer : IComparer<int>
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Compare(int a, int b)
{
if (a == b) { return 0; }
if (a > b) { return -1; }
return 1;
}
}
Span<int> span = GetSomeSpan();
// Sort elements, in reverse order with inlined Compare,
// without heap allocation for comparer
span.Sort(new ReverseComparer()); Sorting based on Lambda
Span<int> span = GetSomeSpan();
// Sort elements, in reverse order with lambda/delegate
span.Sort((a, b) => a == b ? 0 : (a > b ? -1 : 1)); Sorting Compound Type
struct Compound
{
public float FeatureValue;
public int FeatureIndex;
public object Payload;
}
struct InlineableFeatureValueComparer : IComparer<Compound>
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Compare(Compound a, Compound b)
{
if (a.FeatureValue == b.FeatureValue) { return 0; }
if (a.FeatureValue < b.FeatureValue) { return -1; }
return 1;
}
}
var span = new Span<Compound>();
span.Sort();
// Inlineable struct comparer
var comparer = new InlineableFeatureValueComparer();
span.Sort(comparer);
// Lambda comparer
span.Sort((a, b) => a.FeatureValue == b.FeatureValue ? 0 :
(a.FeatureValue < b.FeatureValue ? -1 : 1));The argumentation for adding this is:
- To increase the efficiency of code doing sorting and prevent people from reinventing the wheel.
- Allow performance optimizations depending on memory type and contents.
- Allow sorting on contiguous memory of any kind.
Use Cases
In almost any domain where a high volume of data is processed with sorting being one operation and memory management (e.g. memory recycling, buffer pooling, native memory) is a must to achieve high performance with minimal latency, these sorts would be useful. Example domains are database engines (think indexing), computer vision, artificial intelligence etc.
A concrete example could be in the training of Random Forests some methods employ feature sorting (with indeces) to find decision boundaries on. This involves a lot of data and data that can originate from unmanaged memory.
Open Questions
An important question regarding this proposal is whether the pattern with generic parameter TComparer (e.g. constrained to where TComparer : IComparer<T>) is a pattern that can be approved. This pattern allows for inlineable comparers at the cost of increased code size, if no value type comparers are used, there should be no difference. This pattern is also used in the proposal for BinarySearch in https://github.com/dotnet/corefx/issues/15818
The API relies on being able to depend upon System.Collections.Generic, could this be an issue?
Updates
UPDATE 1: Change API to be defined as extension methods.
UPDATE 2: Add compounded type usage.
UPDATE 3: Add link to BinarySearch and point on the pattern used.
Existing Sort APIs
A non-exhaustive list of existing sorting APIs is given below for comparison.
Array.Sort Static Methods
Found in ref/System.Runtime.cs
public static void Sort(System.Array array) { }
public static void Sort(System.Array keys, System.Array items) { }
public static void Sort(System.Array keys, System.Array items, System.Collections.IComparer comparer) { }
public static void Sort(System.Array keys, System.Array items, int index, int length) { }
public static void Sort(System.Array keys, System.Array items, int index, int length, System.Collections.IComparer comparer) { }
public static void Sort(System.Array array, System.Collections.IComparer comparer) { }
public static void Sort(System.Array array, int index, int length) { }
public static void Sort(System.Array array, int index, int length, System.Collections.IComparer comparer) { }
public static void Sort<T>(T[] array) { }
public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer) { }
public static void Sort<T>(T[] array, System.Comparison<T> comparison) { }
public static void Sort<T>(T[] array, int index, int length) { }
public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer) { }
public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items) { }
public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer) { }
public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length) { }
public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer) { }List<T>.Sort Member Methods
Found in ref/System.Collections.cs
public partial class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
public void Sort() { }
public void Sort(System.Collections.Generic.IComparer<T> comparer) { }
public void Sort(System.Comparison<T> comparison) { }
public void Sort(int index, int count, System.Collections.Generic.IComparer<T> comparer) { }
}LINQ OrderBy Extension Methods
Found in ref/System.Linq.cs
public static System.Linq.IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector) { throw null; }
public static System.Linq.IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Collections.Generic.IComparer<TKey> comparer) { throw null; }
public static System.Linq.IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector) { throw null; }
public static System.Linq.IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Collections.Generic.IComparer<TKey> comparer) { throw null; }
Activity
jkotas commentedon Jan 19, 2017
These should be extension methods. They are in same category as the other similar methods being added: dotnet/corefx#15080
dotnet/corefx#15123
cc @KrzysztofCwalina
nietras commentedon Jan 19, 2017
Ok, would this not mean any optimizations specific to native/managed memory would not be possible as directly as when they are members? Not sure it has such big a relevance since sorting can be done on
refs, but not everything is possible withrefs as with pointers. Anyway, if you think this should not be an issue I will update the proposal.nietras commentedon Jan 19, 2017
Another concern, is generic type inference which in C# is not always working so well with many generic parameters... not that I can think of a specific case for the proposed API though, but in the face of implicit conversions or similar it is often lacking.
jamesqo commentedon Jan 21, 2017
@nietras IMHO, I don't know if this is really a needed API. What scenarios are there in which someone would want to sort a Span? It's mostly going to be used to hold byte/char buffers, where sorting won't make much sense. Also, things like equality comparers are high-level and don't really fit in with low-level constructs like
Span.nietras commentedon Jan 21, 2017
@jamesqo plenty! 😃 Ranging from database engines, computer vision to artificial intelligence. In the latter cases, the types will also range fully from
bytetodouble. And in these fields memory recycling, buffer pooling is paramount to archieving reliable performance. And performance in general important so inlining the compare is important too.Not sure I get that, but is the issue with the "default" comparers needed for
Sort()without parameters? I could live with removing the overloads that do not take aTComparerif that is the concern?svick commentedon Jan 21, 2017
Nitpick: the
Ts in the two lines above should beTKey:nietras commentedon Jan 21, 2017
@svick thanks I also forgot
staticjamesqo commentedon Jan 21, 2017
@nietras
Do you have a concrete example where a sort function would be needed, though? I think the 95% use case for this API would be passing around byte buffers/char buffers. In those scenarios, sorting isn't a function that would be needed, and would only be more API bloat.
The issue, actually, is with the overloads with the comparers. Making them generic on the type of the comparer won't improve perf because everyone passes around comparers as
IEqualityComparer<T>. So you will still have virtual calls.[-]Proposal: Add Span<T>.Sort(...) methods[/-][+]Proposal: Add Sort(...) extension methods for Span<T>[/+]nietras commentedon Jan 22, 2017
@jamesqo I tried giving a more concrete in the proposal regarding machine learning.
If .NET Core and
Span<T>only target audience is web developers, where shuffling bytes to/from text/chars, then perhaps you are right. But IMHO it is a very limited target audience and misses the fact that in a cloud/mobile first world that is going to be infused with artificial intelligence everywhere, handling massive amounts of data/measurements is a must. This includes all data types,bytetodouble. Pure sales talk, uff 🙄I don't and never have. 😉 Passing comparers around is not something we do and it does not have any impact on the design of this API. It still works as a "non-generic" API and if it is only used with reference type comparers there will be no code bloat or anything. So I do not see the downside here, the overloads are there for convenience and flexibility just as with the existing APIs incl.
Array.Sort.The implementation can forward to the same single implementation, for example. However, by having the possibility for using a value type comparer we allow developers that need the perf and understand that this will cause code to be generated specifically for that case to do what they need. No virtual calls. In the domain of numerical processing that is what we need.
KrzysztofCwalina commentedon Jan 23, 2017
We could do Sort(TComparer comparer) where TComparer : IComparer. This would be devirtualized.
jamesqo commentedon Jan 23, 2017
@KrzysztofCwalina It will not unless you pass in a custom struct comparer. For example,
Sort(Comparer<T>.Default)will have TComparer ==Comparer<T>and you will be making virtual calls toComparer<T>.Compare.jamesqo commentedon Jan 23, 2017
There is another thing-- I don't think the overloads accepting
TComparerwill even compile. See here. I ran into this issue a few months ago when I was trying to use generics in a similar fashion.39 remaining items
stephentoub commentedon Jun 12, 2020
From my perspective, we should either remove the generic parameter or avoid the boxing. My preference is the former; I don't think having it be generic over the comparer type adds enough benefit to counteract the cost and complexity (even the array-sorting overload that takes an interface allocates an object).
@jkotas, do you have an opinion?
jkotas commentedon Jun 12, 2020
@stephentoub I agree with your assessment.
Sergio0694 commentedon Jun 12, 2020
Oh I'm sorry to hear that, I thought the direction with a heavier usage of generics to squeeze out more performance was actually pretty great. Just as an idea, if the concern is the increased code size with the two implementations (the generic one, and the one using
Comparison<T>), wouldn't it be possible to introduce a new (internal) type like this one, to wrapIComparer<T>values:And then make the
ArraySortHelper<T>type always be generic in both the item type and the comparison type? This could use either the user-specific comparer if one is provided, or in the other paths for all the current APIs it'd just wrap the suppliedComparison<T>delegate into an instance of thisValueComparer<T>struct and just pass that around? This would allow to have a single implementation that would work in both cases. Shouldn't the performance improvement in the case that a generic comparer is supplied by the user be worth the time to make this change?As another example, in the case where
T : IComparable<T>, users could just pass this:And it would basically be free performance, as the sort algorithm could then always inline this and skip one indirect call that it's not doing for each single comparison, to that
Comparison<T>instance.As an example, we're now using this same approach in
ImageSharpas well (here) (I actually got the original idea for this frombepuphysics2), and I've added similar APIs to theMicrosoft.Toolkit.HighPerformancepackage as well (here). In my tests, there was a very decent performance improvement when the supplied "value delegate" was small enough to be inlined, which I guess would be desireable especially for users trying to sort aSpan<T>in the first place?Just a thought, I understand there might be other factors here I'm not properly considering 😊
nietras commentedon Jun 12, 2020
@Sergio0694 I tried to consolidate the sorting code based on the patterns you describe (going down the value type comparers rabbit hole futilely), but sadly the performance of this simply isn't there due to limitations in the runtime currently (inlining, CG, etc.). The canonical representation of generic types for reference type generic parameters is an issue too (the main issue, while the pattern works wonders for value types it doesn't for reference types, I have spent an exorbitant amount of time looking into this 🤦♂️ ). Haven't completely given up consolidating some here with the advent of function pointers in C# 9, but the reality is I had to create 4 versions of sorting code to get decent perf. Or in some cases 1.66x better perf than what is in .NET 5 now. At least last I benchmarked.
@stephentoub @jkotas I, of course 😃 , disagree with this. I specifically designed the API around being able to define value type comparers for inlineable custom comparisons, which can have significant performance improvements for custom scenarios. Not all of users are sorting primitives only. If you remove it from the API, this could tie the API down for the future.
On the other hand, if I finish
DotNetCross.Sortingthis could be available outside of BCL and hence fulfil this requirement. But it is a heavy burden to bear 😅 Fast and flexible sorting is in my view a fundamental part of a great platform.stephentoub commentedon Jun 12, 2020
If we have:
now, what prevents us from adding:
as an overload later?
Right now the overload is a pit of failure: someone tries to use a struct TComparer thinking it'll avoid allocations and enable devirtualization and inlining, and not only does it not enable devirtualization and inlining, it actually results in two allocations.
nietras commentedon Jun 12, 2020
Nothing, except of course poor overload resolution 😅 Especially, if implicit conversions are considered. But that may not be a big concern. I hope you will keep it though and that we could find a solution to the implementation issue. Either using source generator or something. Would it be a problem to have multiple versions of sorting code if they were generated? Only one version to maintain? Is the main objection to the API the runtime code generation cost e.g. instruction as bytes?
nietras commentedon Jun 12, 2020
@stephentoub it's pretty bad now yes 😅. I am not a fan of the forced allocations going on for sure. Including for a reference type comparer since this gets converted to a delegate. This can be solved simply by adding appropriate code for it, though. It's not hard to add, it just another "variant".
nietras commentedon Jun 12, 2020
@stephentoub I would also encourage you to look at
floatsorting performance in .NET 5 compared to the native in .NET Core 3.1. As far as I can tell it is not on par, due to problems with inliningCompareTo. That's why my version gets a decent perf boost compared to .NET 5. Example given below, not exactly 1.66x in this but definitely significantly faster. Note this was preview.2 though. 😃nietras commentedon Jun 12, 2020
Of course this perf boost is nothing compared to @damageboy VxSort. Nothing compares to that 🚀
stephentoub commentedon Jun 12, 2020
In what way?
We're close to being done with .NET 5. What solution are you proposing to implement? The current API is the worst of all relevant worlds: it has a more complicated and intimidating signature, it doesn't provide the intended benefits, and it leads one to use a coding style (using a struct and not caching an instance) that leads to worse performance than if a simple lambda were just used. You can also get the same advanced benefits by sorting structs with custom
IComparable<T>implementations (though I understand that represents only a portion of the scenarios trying to be optimized.)Yes, a lot of duplicated code, when we're already facing more duplication than we'd like.
If you really believe this is critical, show us what the complete solution looks like.
That is unrelated to this API; you didn't show your code, but the perf should be comparable between 3.1 and 5 without a supplied comparer and just using the type's
IComparable<T>implementation. So if it's not, please open a separate issue.nietras commentedon Jun 12, 2020
The code is here https://github.com/DotNetCross/Sorting/tree/master/src/DotNetCross.Sorting/Implementations and is a mayhem of 2 x 4 variant == 8 copies. I have pointed to this before. Note this code was explicitly split up to show this in detail and to show the parts of the sorting. Probably not to every bodies liking. No reason this couldn't be generated, although I see perf issues for special cases. Note also these implementations are based on a "pure"
refs andUnsafecode since this has to work well on old runtimes.I still think there is a "solution" to the canonical representation issue, but the JIT has too many issues around inlining (doesn't inline methods with delegates for example 🤷♂️) which I have commented on in other places. So I have given up on that honestly.
I'm fine with keeping this in a separate repo/nuget package. If no value can be seen in having this in the BCL.
Sergio0694 commentedon Jun 12, 2020
Yes, I definitely can't disagree with that. My first thought when seeing that API was like "Ah, great! It's nice they went full-on generic for best performance", then just decided to check the source out of curiosity and discovered that that was actually a lie 🤣
Ah, I just noticed there's a separate generic array sort helper for that case, missed that earlier.
I wonder if in cases where you just do a check for
CompareTo(y) >= 0, the JIT is able to just inline the completely and just literally emit a single comparison for primitive types. I mean, sinceCompareTowould normally have a couple conditional branches otherwise 🤔I'd test this out but sharplab.io is down right now 😆
nietras commentedon Jun 12, 2020
For
intit does. Forfloatit doesn't. Hence, why I have aTDirectComparerversion. Depends highly on the code around and the optimizations being done. You are basically praying to the JIT gods that this code quality will be good. Again these observations are points in time. The runtime changes/improves here. But if you are on an older runtime and can't switch you can't rely on these improvements.nietras commentedon Jun 12, 2020
IComparer<T>is a bit of a problem at least for sorting. For sorting it would be better to just have an interface like:same for
IComparable<T>. But that's history. :)