Tips and Tricks #65: Use Span for Zero-Allocation String Parsing

Eliminate heap allocations when parsing strings by using Span for memory-efficient operations.

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 cannot be used in async methods or stored in class fields. Use Memory for those cases.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.