diff --git a/docs/core/whats-new/dotnet-8/runtime.md b/docs/core/whats-new/dotnet-8/runtime.md index fe2f861165da6..7d826930e87c6 100644 --- a/docs/core/whats-new/dotnet-8/runtime.md +++ b/docs/core/whats-new/dotnet-8/runtime.md @@ -514,6 +514,7 @@ IDataView predictions = model.Transform(split.TestSet); ``` - Methods like look for the first occurrence of *any value in the passed collection*. The new type is designed to be passed to such methods. Correspondingly, .NET 8 adds new overloads of methods like that accept an instance of the new type. When you create an instance of , all the data that's necessary to optimize subsequent searches is derived *at that time*, meaning the work is done up front. + - The new type is useful for optimizing format strings that aren't known at compile time (for example, if the format string is loaded from a resource file). A little extra time is spent up front to do work such as parsing the string, but it saves the work from being done on each use. ```csharp diff --git a/docs/standard/base-types/string-comparison-net-5-plus.md b/docs/standard/base-types/string-comparison-net-5-plus.md index 5ea0b746a766f..070b2855da592 100644 --- a/docs/standard/base-types/string-comparison-net-5-plus.md +++ b/docs/standard/base-types/string-comparison-net-5-plus.md @@ -331,6 +331,37 @@ ReadOnlySpan span = s.AsSpan(); if (span.StartsWith("Hello", StringComparison.Ordinal)) { /* do something */ } // ordinal comparison ``` +## Efficient multi-value string comparisons + +Starting with .NET 8, when comparing a string against a fixed set of known values repeatedly, consider using instead of chained comparisons or LINQ-based approaches. +`SearchValues` can precompute internal lookup structures and optimize the comparison logic based on the provided values. + +### Recommended usage + +Create and cache the `SearchValues` instance once, then reuse it for comparisons: + +```cs +using System.Buffers; + +private static readonly SearchValues Commands = SearchValues.Create(new[] { "start", "run", "go" }, StringComparison.OrdinalIgnoreCase); + +if (Commands.Contains(command)) +{ + /* do something */ +} +``` +### Avoid repeated creation +Avoid creating `SearchValues` instances inside hot paths or per comparison, as the creation step can be relatively expensive: + +```cs +// Avoid this pattern +if (SearchValues.Create(new[] { "start", "run", "go" }, StringComparison.OrdinalIgnoreCase).Contains(command)) +{ + /* do something */ +} +``` +Caching and reusing the instance ensures optimal performance. + ## See also - [Globalization breaking changes in .NET 5](../../core/compatibility/5.0.md#globalization)