All rules
CA1870Performance Enabled by default: As suggestion

Use a cached 'SearchValues' instance

Use a cached 'SearchValues' instance

Microsoft docs

Description

Using a cached System.Buffers.SearchValues1 instance is more efficient than passing values to IndexOfAny or ContainsAny` directly.

Cause

An IndexOfAny or ContainsAny method is called with many constant values in a way that can benefit from using System.Buffers.SearchValues instead.

The rule doesn't flag calls that use up to five values, as those already use an optimal implementation.

How to fix violations

Create and cache a System.Buffers.SearchValues1 instance in a static readonly field, then pass that instance to the IndexOfAny or ContainsAny` call instead.

A *code fix* that automatically performs this transformation is available.

Example

static readonly char[] MyValues = new[] { 'a', 'b', 'c', 'x', 'y', 'z' };

static int IndexOfMyValues(ReadOnlySpan<char> text)
{
    return text.IndexOfAny(MyValues);
}

static bool ContainsOnlyMyValues(ReadOnlySpan<char> text)
{
    return !text.ContainsAnyExcept("abcxyz");
}

private static readonly SearchValues<char> s_myValues = SearchValues.Create("abcxyz");

static int IndexOfMyValues(ReadOnlySpan<char> text)
{
    return text.IndexOfAny(s_myValues);
}

static bool ContainsOnlyMyValues(ReadOnlySpan<char> text)
{
    return !text.ContainsAnyExcept(s_myValues);
}

When to suppress

It's safe to suppress this warning if performance isn't a concern.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0