Optimizing .NET: Day 2
From December 1 through Christmas Eve, I’ll cover one .NET runtime-library optimization a day.
Enumerable.Intersect()#
int[] requested = [7, 2, 7, 5, 0];
int[] enabled = [0, 7, 7, 3];
int[] matches = requested.Intersect(enabled).ToArray();
// matches is [7, 0]
LINQ's Intersect() builds a hash set from the second sequence and removes each key as it yields a match. That's a lot of work (hashcode generation, equality checks, modulo reduction) for an array that small! Instead, we could pack it all into a vector and compare all the entries at once. A bit mask clears every matching lane before the value is yielded, which preserves the first sequence's order and removes duplicates.
The same SIMD code works for all ten primitive integer types. The patch picks the smallest hardware-accelerated vector that can hold all the keys.
| Element width | Integer types | 128 bits | 256 bits | 512 bits |
|---|---|---|---|---|
| 8 bits | byte, sbyte |
16 | 32 | 64 |
| 16 bits | short, ushort |
8 | 16 | 32 |
| 32 bits | int, uint |
4 | 8 | 16 |
| 64 bits | long, ulong |
2 | 4 | 8 |
nint and nuint use the row for the process's pointer size.
The fast path needs default equality and a nonempty integer array that fits in one accelerated vector. Other inputs use the hash set.
if ((Vector128.IsHardwareAccelerated || Vector256.IsHardwareAccelerated || Vector512.IsHardwareAccelerated) && Vector128<TSource>.IsSupported &&
typeof(TSource) != typeof(float) && typeof(TSource) != typeof(double) && second.GetType() == typeof(TSource[]) &&
(comparer is null || ReferenceEquals(comparer, EqualityComparer<TSource>.Default)))
{
TSource[] keys = (TSource[])second;
uint lastIndex = (uint)(keys.Length - 1);
if (Vector128.IsHardwareAccelerated && lastIndex < Vector128<TSource>.Count)
return IntersectSmallIntegerArray<TSource, Vector128<TSource>, uint>(first, keys);
if (Vector256.IsHardwareAccelerated && lastIndex < Vector256<TSource>.Count)
return IntersectSmallIntegerArray<TSource, Vector256<TSource>, uint>(first, keys);
if (Vector512.IsHardwareAccelerated && lastIndex < Vector512<TSource>.Count)
return IntersectSmallIntegerArray<TSource, Vector512<TSource>, ulong>(first, keys);
}
return IntersectIterator(first, second, comparer);
The iterator snapshots the keys when enumeration begins. A key array that fills the chosen vector uses an unaligned load. A shorter array is copied into a zero-initialized vector. The JIT folds the width tests in MatchLanes, and the iterator keeps a 32-bit mask for 128- and 256-bit vectors and a 64-bit mask for 512-bit vectors.
Show the iterator
private static IEnumerable<TSource> IntersectSmallIntegerArray<TSource, TVector, TMask>(IEnumerable<TSource> first, TSource[] second)
where TVector : struct
where TMask : struct, IBinaryInteger<TMask>
{
// Snapshot the keys at enumeration start, as the HashSet path does.
TVector keys;
int laneCount = Unsafe.SizeOf<TVector>() / Unsafe.SizeOf<TSource>();
// A key array that fills the vector loads directly. The padded copy below calls Memmove,
// which measurably slows queries that stop after the first few matches.
if (second.Length == laneCount)
{
ref TSource firstKey = ref MemoryMarshal.GetArrayDataReference(second);
keys = Unsafe.ReadUnaligned<TVector>(ref Unsafe.As<TSource, byte>(ref firstKey));
}
else
{
keys = default;
second.AsSpan().CopyTo(MemoryMarshal.CreateSpan(ref Unsafe.As<TVector, TSource>(ref keys), laneCount));
}
// Keep 32-bit masks where they suffice. A 64-bit mask for every width costs an extra
// register move before each AND and measured slower.
TMask remaining = TMask.AllBitsSet >> (Unsafe.SizeOf<TMask>() * 8 - second.Length);
foreach (TSource element in first)
{
if (remaining != TMask.Zero)
{
TMask matches = MatchLanes<TSource, TVector, TMask>(in keys, element) & remaining;
if (matches != TMask.Zero)
{
remaining &= ~matches;
yield return element;
}
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static TMask MatchLanes<T, TVector, TMask>(in TVector keys, T element)
where TVector : struct
where TMask : struct
{
if (typeof(TVector) == typeof(Vector128<T>))
{
ref Vector128<T> vector = ref Unsafe.As<TVector, Vector128<T>>(ref Unsafe.AsRef(in keys));
uint matches = Vector128.Equals(vector, Vector128.Create(element)).ExtractMostSignificantBits();
return Unsafe.BitCast<uint, TMask>(matches);
}
if (typeof(TVector) == typeof(Vector256<T>))
{
ref Vector256<T> vector = ref Unsafe.As<TVector, Vector256<T>>(ref Unsafe.AsRef(in keys));
uint matches = Vector256.Equals(vector, Vector256.Create(element)).ExtractMostSignificantBits();
return Unsafe.BitCast<uint, TMask>(matches);
}
ref Vector512<T> wide = ref Unsafe.As<TVector, Vector512<T>>(ref Unsafe.AsRef(in keys));
ulong wideMatches = Vector512.Equals(wide, Vector512.Create(element)).ExtractMostSignificantBits();
return Unsafe.BitCast<ulong, TMask>(wideMatches);
}
All 50 Intersect tests passed on stock and patched .NET 11, including tests at the byte lane limits, deferred enumeration, and floating-point equality.
Benchmark#
FirstMatch intersects a 16-element integer array with four keys and returns the first match. The match is the third source element, so one operation consumes 28 B of logical input from the four keys and three source elements.
| Metric | Before | After | Change |
|---|---|---|---|
| Mean latency (ns/op) | 70.00 | 23.21 | 66.8% lower |
| Managed allocation (B/op) | 392 | 128 | 67.3% lower |
| Throughput (MB/s) | 400 | 1,206 | 201.5% higher |
Results
| Method | Job | Mean | Error | StdDev | Ratio | Allocated | Alloc Ratio |
|---|---|---|---|---|---|---|---|
| FirstMatch | stock | 70.00 ns | 5.944 ns | 3.537 ns | 1.00 | 392 B | 1.00 |
| FirstMatch | patched | 23.21 ns | 2.082 ns | 1.377 ns | 0.33 | 128 B | 0.33 |
| RepeatedValues | stock | 1,010.50 ns | 83.825 ns | 49.883 ns | 1.00 | 392 B | 1.00 |
| RepeatedValues | patched | 358.62 ns | 11.117 ns | 5.814 ns | 0.36 | 128 B | 0.33 |
| ByteKeys32 | stock | 1,030.7 ns | 42.91 ns | 28.38 ns | 1.00 | 872 B | 1.00 |
| ByteKeys32 | patched | 381.2 ns | 12.30 ns | 7.32 ns | 0.37 | 144 B | 0.17 |
| Int32Keys5 | stock | 870.2 ns | 41.62 ns | 27.53 ns | 1.00 | 392 B | 1.00 |
| Int32Keys5 | patched | 370.4 ns | 14.61 ns | 8.69 ns | 0.43 | 144 B | 0.37 |
| ByteKeys33 | stock | 1,115.6 ns | 101.02 ns | 66.82 ns | 1.00 | 872 B | 1.00 |
| ByteKeys33 | patched | 757.7 ns | 27.69 ns | 14.48 ns | 0.68 | 872 B | 1.00 |
Reproduce#
With the .NET 11 SDK installed, run this from the extracted benchmark directory.
dotnet run -c Release
The benchmark loads the bundled stock and patched libraries. Both were built from dotnet/runtime commit deae2e32bf0e018e09d64597b7c59b62b73bb3ce.