From b0c7ded2f8657510bb484ae29dcf1e4dffbc0acd Mon Sep 17 00:00:00 2001 From: Miha Zupan Date: Sat, 22 Apr 2023 22:06:35 +0200 Subject: [PATCH] Improve ProbabilisticMap performance for small value sets --- .../IndexOfAnyCharValuesProbabilistic.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/IndexOfAnyValues/IndexOfAnyCharValuesProbabilistic.cs b/src/libraries/System.Private.CoreLib/src/System/IndexOfAnyValues/IndexOfAnyCharValuesProbabilistic.cs index 0838d480dbeb1..1600cec5b4fc6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IndexOfAnyValues/IndexOfAnyCharValuesProbabilistic.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IndexOfAnyValues/IndexOfAnyCharValuesProbabilistic.cs @@ -3,6 +3,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; namespace System.Buffers { @@ -11,8 +12,18 @@ internal sealed class IndexOfAnyCharValuesProbabilistic : IndexOfAnyValues private ProbabilisticMap _map; private readonly string _values; - public unsafe IndexOfAnyCharValuesProbabilistic(ReadOnlySpan values) + public IndexOfAnyCharValuesProbabilistic(scoped ReadOnlySpan values) { + if (Vector128.IsHardwareAccelerated && values.Length < 8) + { + // ProbabilisticMap does a Span.Contains check to confirm potential matches. + // If we have fewer than 8 values, pad them with existing ones to make the verification faster. + Span newValues = stackalloc char[8]; + newValues.Fill(values[0]); + values.CopyTo(newValues); + values = newValues; + } + _values = new string(values); _map = new ProbabilisticMap(_values); }