Pattern Matching on Spans and UTF-8 Literals in C# 15 / .NET 11
High-throughput network parsers (Kestrel, custom TCP, Kafka consumers) read wire data as ReadOnlySpan . Historically, running a clean switch statement on headers or commands required either string transcoding with Encoding.UTF8.GetString or chaining verbose SequenceEqual("...u8) checks. Before // Allocates a string on Gen0 for every wire message var method = Encoding . UTF8 . GetString ( buffer )…
Beginning with high-throughput network parsers like Kestrel, custom TCP, and Kafka consumers, reading wire data as ReadOnlySpan<byte> has long necessitated either converting the data to a string via Encoding.UTF8.GetString or performing verbose SequenceEqual("...u8) checks when constructing switch statements for headers or commands. Before the introduction of C# 15 and .NET 11, developers faced the inconvenience of allocating a string on Gen0 for each wire message.
Now, with the release of C# 15 and .NET 11, a significant improvement has arrived in the form of direct switch pattern matching on byte spans. The updated code snippet demonstrates this advancement: return buffer switch { "GET" u8 = HttpMethod.Get, "POST" u8 = HttpMethod.Post, _ = HttpMethod.Custom }. This change offers multiple benefits:
Firstly, it eliminates zero allocations, thereby eradicating any Gen0 garbage collection pressure within the hot loop parser paths. Secondly, the JIT compiler can transform these literal comparisons into tight branch tables and SIMD sequence checks without the overhead of intermediate pointers. Lastly, the readability of the code has been enhanced, replacing verbose if (buffer.SequenceEqual("GET"u8)) chains with the idiomatic pattern matching syntax.
However, it is crucial to note that span pattern matching evaluates ordinal byte equivalence. Therefore, if the wire protocol is case-insensitive, developers must canonicalize the slice into a scratch span before performing the pattern match. This ensures accurate results. The question remains: have you managed to eliminate all string transcoding from your ingest pipelines?
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to