Skip to content

Files

Latest commit

 

History

History
43 lines (30 loc) · 972 Bytes

File metadata and controls

43 lines (30 loc) · 972 Bytes

Pattern: Missing use of cached SearchValues<T>

Issue: -

Description

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);
}

Further Reading