| description | Use when writing or modifying C# code in SortingNetworks. Covers performance-critical patterns: Unsafe, refs, AggressiveInlining, zero-allocation sorting. |
|---|---|
| applyTo | **/*.cs |
This is a high-performance sorting library. All code in the hot path must follow these rules:
- Use
refandUnsafe.Add(ref T, int)for element access instead of span indexing in unrolled methods. - Use
MemoryMarshal.GetReference(span)to get a ref to the first element. - Mark hot-path private methods with
[MethodImpl(MethodImplOptions.AggressiveInlining)]. - Avoid heap allocations in sort methods — no LINQ, no closures, no boxing.
- Use platform-specific compare-and-swap for numeric primitive types (
byte,sbyte,short,ushort,int,uint,long,ulong,float,double). By default, the generator emits a runtimeX86Base.IsSupportedcheck: branchlessMath.Min/Math.Maxon x86 (JIT lowers tocmov), branchingif/swapon ARM (where branch prediction outperformscselchains). TheBranchlessattribute property can force one strategy:[SortingNetwork(27, typeof(int), Branchless = true)]. Forcharand custom types, always use branchingif (a > b) { T temp = a; a = b; b = temp; }. - NaN is not supported for
float/doublesorting. Sorting networks use ordered comparisons whereNaN > xis always false, so NaN values disrupt sort order. See #10 and #11. IComparer<T>overloads use the loop-basedApplyNetworkWithComparerpath and are not unrolled.- Fallback to
span.Sort()orArray.Sort()for sizes outside the network range. AllowUnsafeBlocksis enabled in the project.