DEV Community

Cover image for SearchValues<T> in .NET 8/9 (.NET & C#)
Maayur Dahake
Maayur Dahake

Posted on

SearchValues<T> in .NET 8/9 (.NET & C#)

Day 1/30 — SearchValues in .NET 8/9 (.NET & C#)

Spotted a hot path in a string parser allocating megabytes on Gen0 just checking punctuation marks.

Before:

if (input.Contains(',') || input.Contains(';')) {
    // Triggers internal array allocations
}
Enter fullscreen mode Exit fullscreen mode

After:

private static readonly SearchValues<char> S = SearchValues.Create(",;");
if (input.AsSpan().ContainsAny(S)) {
    // Executes via vectorized CPU instructions
}
Enter fullscreen mode Exit fullscreen mode

Why it matters:
• SearchValues Cache: Pre-computes lookup tables once at startup to avoid repeated overhead.
• SIMD Vectorization: Processes 16 to 64 bytes per CPU cycle depending on hardware vector width.
• Zero Allocations: Operates entirely on ReadOnlySpan without boxing or heap pressure.

Watch out: Creating the SearchValues instance inside a tight loop negates all performance gains.

What is your go-to trick for reducing string parser allocations?

DotNet #CSharp #Performance #BackendDevelopment #SoftwareEngineering

Top comments (0)