Pattern: Missing use of cached SearchValues<T>
Issue: -
Using a cached SearchValues<T>
instance is more efficient than passing values to IndexOfAny
or ContainsAny
directly.
Example of incorrect code:
static readonly char[] TestValues = new[] { 'a', 'b', 'c', 'x', 'y', 'z' };
static int IndexOfTest(ReadOnlySpan<char> text)
{
return text.IndexOfAny(TestValues);
}
static bool ContainsOnlyTest(ReadOnlySpan<char> text)
{
return !text.ContainsAnyExcept("abcxyz");
}
Example of correct code:
private static readonly SearchValues<char> searchValues = SearchValues.Create("abcxyz");
static int IndexOfTest(ReadOnlySpan<char> text)
{
return text.IndexOfAny(searchValues);
}
static bool ContainsOnlyTest(ReadOnlySpan<char> text)
{
return !text.ContainsAnyExcept(searchValues);
}