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
}
After:
private static readonly SearchValues<char> S = SearchValues.Create(",;");
if (input.AsSpan().ContainsAny(S)) {
// Executes via vectorized CPU instructions
}
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?
Top comments (0)