CA1870: Use a cached 'SearchValues' instance
Property | Value |
---|---|
Rule ID | CA1870 |
Title | Use a cached 'SearchValues' instance |
Category | Performance |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 9 | As suggestion |
Cause
An IndexOfAny
or ContainsAny
method is called with many constant values in a way that can benefit from using SearchValues instead.
The rule doesn't flag calls that use up to five values, as those already use an optimal implementation.
Rule description
Using a cached SearchValues<T> instance is more efficient than passing values to IndexOfAny
or ContainsAny
directly.
How to fix violations
Create and cache a SearchValues<T> instance in a static readonly
field, then pass that instance to the IndexOfAny
or ContainsAny
call instead.
A code fixer that performs this transformation is available.
Example
The following code snippet shows two violations of CA1870:
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");
}
The following code snippet fixes the violations:
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);
}
If there are multiple calls to IndexOfAny
with the same set of values, s_myValues
should be reused.
When to suppress warnings
It's safe to suppress this warning if performance isn't a concern.
Suppress a warning
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA1870
// The code that's violating the rule is on this line.
#pragma warning restore CA1870
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1870.severity = none
For more information, see How to suppress code analysis warnings.