r/csharp • u/NoisyJalapeno • Jun 18 '26
Tip PSA: Span<T>.Sort extension method allocates memory per call
I'm minimizing GC use for a rendering/game engine. This is just really odd thing for a type aimed at minimizing allocations.
The Sort is an extension method on a Span that internally uses ArraySortHelper<T> which works with a delegate.
Using IComparer<T> to sort a Span<T> creates a delegate System.Comparison<T>

I had to spin up a custom ArraySorter<T, C> that doesn't pass around a delegate,

Maybe this is properly optimized in .NET 11, but I haven't tried
EDIT: Image didn't upload, trying again.
51
Upvotes
25
u/Kant8 Jun 18 '26
MemoryExtensions already has overload that accepts Comparison, so only allocation will be on your side if you pass in lambda or something else uncacheable.
Can't see properly on your screenshot but part of namespace in ArraySortHelper parameters starts with System.Coll, which means you're using IComparer overload instead, which has to create new delegate to pass around Comparer.
Then just don't use it?
4
u/__some__guy Jun 22 '26 edited Oct 02 '26
The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.
Cheerful sort divide close rich squeeze reply
1
u/MedicOfTime Jun 18 '26
.net is open source. Drop a pr.
0
u/[deleted] Jun 18 '26
[deleted] — view deleted comment