diff --git a/src/libraries/System.Linq/src/System/Linq/Intersect.cs b/src/libraries/System.Linq/src/System/Linq/Intersect.cs --- a/src/libraries/System.Linq/src/System/Linq/Intersect.cs +++ b/src/libraries/System.Linq/src/System/Linq/Intersect.cs @@ -2,6 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; namespace System.Linq { @@ -19,6 +23,29 @@ if (second is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.second); + } + + if ((Vector128.IsHardwareAccelerated || Vector256.IsHardwareAccelerated || Vector512.IsHardwareAccelerated) && + Vector128.IsSupported && + typeof(TSource) != typeof(float) && + typeof(TSource) != typeof(double) && + second.GetType() == typeof(TSource[]) && + (comparer is null || ReferenceEquals(comparer, EqualityComparer.Default))) + { + TSource[] keys = (TSource[])second; + uint lastIndex = (uint)(keys.Length - 1); + if (Vector128.IsHardwareAccelerated && lastIndex < Vector128.Count) + { + return IntersectSmallIntegerArray, uint>(first, keys); + } + if (Vector256.IsHardwareAccelerated && lastIndex < Vector256.Count) + { + return IntersectSmallIntegerArray, uint>(first, keys); + } + if (Vector512.IsHardwareAccelerated && lastIndex < Vector512.Count) + { + return IntersectSmallIntegerArray, ulong>(first, keys); + } } return IntersectIterator(first, second, comparer); @@ -73,6 +100,66 @@ return IntersectByIterator(first, second, keySelector, comparer); } + private static IEnumerable IntersectSmallIntegerArray(IEnumerable first, TSource[] second) + where TVector : struct + where TMask : struct, IBinaryInteger + { + // Snapshot the keys at enumeration start, as the HashSet path does. + TVector keys; + int laneCount = Unsafe.SizeOf() / Unsafe.SizeOf(); + // 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(ref Unsafe.As(ref firstKey)); + } + else + { + keys = default; + second.AsSpan().CopyTo(MemoryMarshal.CreateSpan(ref Unsafe.As(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() * 8 - second.Length); + + foreach (TSource element in first) + { + if (remaining != TMask.Zero) + { + TMask matches = MatchLanes(in keys, element) & remaining; + if (matches != TMask.Zero) + { + remaining &= ~matches; + yield return element; + } + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static TMask MatchLanes(in TVector keys, T element) + where TVector : struct + where TMask : struct + { + if (typeof(TVector) == typeof(Vector128)) + { + ref Vector128 vector = ref Unsafe.As>(ref Unsafe.AsRef(in keys)); + uint matches = Vector128.Equals(vector, Vector128.Create(element)).ExtractMostSignificantBits(); + return Unsafe.BitCast(matches); + } + if (typeof(TVector) == typeof(Vector256)) + { + ref Vector256 vector = ref Unsafe.As>(ref Unsafe.AsRef(in keys)); + uint matches = Vector256.Equals(vector, Vector256.Create(element)).ExtractMostSignificantBits(); + return Unsafe.BitCast(matches); + } + + ref Vector512 wide = ref Unsafe.As>(ref Unsafe.AsRef(in keys)); + ulong wideMatches = Vector512.Equals(wide, Vector512.Create(element)).ExtractMostSignificantBits(); + return Unsafe.BitCast(wideMatches); + } + private static IEnumerable IntersectIterator(IEnumerable first, IEnumerable second, IEqualityComparer? comparer) { var set = new HashSet(second, comparer); diff --git a/src/libraries/System.Linq/tests/IntersectTests.cs b/src/libraries/System.Linq/tests/IntersectTests.cs --- a/src/libraries/System.Linq/tests/IntersectTests.cs +++ b/src/libraries/System.Linq/tests/IntersectTests.cs @@ -44,6 +44,54 @@ { Assert.Equal(expected, first.Intersect(second)); Assert.Equal(expected, first.Intersect(second, null)); + } + + [Theory] + [InlineData(16)] + [InlineData(17)] + [InlineData(32)] + [InlineData(33)] + [InlineData(64)] + [InlineData(65)] + public void ByteKeysAtVectorBoundaries(int keyCount) + { + byte last = (byte)keyCount; + byte[] first = [0, last, 1, last, 1]; + byte[] second = Enumerable.Range(1, keyCount).Select(value => (byte)value).ToArray(); + + Assert.Equal([last, 1], first.Intersect(second, EqualityComparer.Default)); + } + + [Fact] + public void ByteArraySecondIsSnapshottedOnEachEnumeration() + { + byte[] first = [0, 1, 2, 2, 3, 4]; + byte[] second = [1, 2, 2]; + IEnumerable query = first.Intersect(second); + second[0] = 3; + + using (IEnumerator enumerator = query.GetEnumerator()) + { + Assert.True(enumerator.MoveNext()); + Assert.Equal(2, enumerator.Current); + Array.Fill(second, 4); + Assert.True(enumerator.MoveNext()); + Assert.Equal(3, enumerator.Current); + Assert.False(enumerator.MoveNext()); + } + + Assert.Equal([4], query); + } + + [Fact] + public void SingleKeysUseDefaultEquality() + { + float nan = BitConverter.Int32BitsToSingle(0x7FC00001); + float[] first = [nan, -0.0f, float.NaN, 0.0f]; + float[] second = [0.0f, float.NaN]; + int[] expected = [BitConverter.SingleToInt32Bits(nan), int.MinValue]; + + Assert.Equal(expected, first.Intersect(second).Select(BitConverter.SingleToInt32Bits)); } public static IEnumerable String_TestData() # End of patch