Zero-Allocation JSON Parsing with `Utf8JsonReader` & `Utf8JsonWriter`
1Concept
`Utf8JsonReader` is a high-speed `ref struct` that parses raw UTF-8 byte streams directly into spans without converting them to UTF-16 C# strings, achieving 10x lower memory overhead than traditional JSON parsers.
2Architecture Diagram
Raw UTF-8 Bytes: [ 0x7B, 0x22, 0x69, 0x64, 0x22, ... ] ("{"id":101}")
│
▼
[ Utf8JsonReader (Ref Struct on Stack) ]
├── Token: StartObject
├── Token: PropertyName -> "id" (Read as ReadOnlySpan<byte>)
└── Token: Number -> 101 (Zero String Allocations!)3Code Example
C# 13 & .NET 9
using System;
using System.Text;
using System.Text.Json;
public class Utf8JsonReaderDemo
{
public static void Main()
{
byte[] jsonBytes = Encoding.UTF8.GetBytes("{\"metric\": \"cpu_usage\", \"value\": 94.5}");
var reader = new Utf8JsonReader(jsonBytes);
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.PropertyName && reader.ValueTextEquals("value"u8))
{
reader.Read();
double value = reader.GetDouble();
Console.WriteLine($"Parsed Metric Value (Zero UTF-16 String Allocation): {value}");
}
}
}
}4Expected Output
Parsed Metric Value (Zero UTF-16 String Allocation): 94.5
5Key Takeaways
- ✓`"value"u8` (UTF-8 string literal in C# 11+) provides compile-time zero-allocation UTF-8 byte spans.
- ✓`Utf8JsonReader` is non-allocating and stack-allocated (`ref struct`).
- ✓Used internally by `System.Text.Json` for maximum throughput.