Eliminate heap allocations when parsing strings by using Span
Code Snippet
// Before: Creates new string allocations
string input = "key=value";
string[] parts = input.Split('=');
string key = parts[0];
string value = parts[1];
// After: Zero allocations with Span
ReadOnlySpan span = input.AsSpan();
int index = span.IndexOf('=');
ReadOnlySpan key = span[..index];
ReadOnlySpan value = span[(index + 1)..];
Why This Helps
- Eliminates temporary string allocations in hot paths
- Reduces GC pressure significantly in high-throughput scenarios
- Works seamlessly with existing string APIs
How to Test
- Use BenchmarkDotNet to compare allocation counts
- Profile with dotMemory to verify zero allocations
When to Use
High-frequency parsing operations, API request handling, log processing pipelines.
Performance/Security Notes
Span
References
Try this tip in your next project and share your results in the comments!
Discover more from Code, Cloud & Context
Subscribe to get the latest posts sent to your email.