Home / Forums / Zero-Allocation JSON Serialization with Utf8JsonWriter and IBufferWriter<byte>

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Tutorial

Zero-Allocation JSON Serialization with Utf8JsonWriter and IBufferWriter<byte>

JsonSpeedster
Serialization & I/O
MEMBER
Rep: 82
Join Date: Jun 2025
Posts: 7
Thanks: 87
2y ago · Aug 25, 2023 2:10 PM
#1
Standard
CODE
JsonSerializer.Serialize()
produces a
CODE
string
, which requires a UTF-16 heap allocation and subsequent UTF-8 encoding when writing to a network socket.

How to write JSON directly into UTF-8 byte streams with zero string allocations:

CSHARP
using System.Buffers;
using System.Text.Json;

public static class FastJsonSerializer
{
    public static void WritePlayerState(IBufferWriter<byte> bufferWriter, int playerId, string username, float health)
    {
        using var writer = new Utf8JsonWriter(bufferWriter, new JsonWriterOptions { Indented = false });
        
        writer.WriteStartObject();
        writer.WriteNumber("id", playerId);
        writer.WriteString("user", username);
        writer.WriteNumber("hp", health);
        writer.WriteBoolean("alive", health > 0);
        writer.WriteEndObject();
        
        writer.Flush();
    }
}


Combining
CODE
Utf8JsonWriter
with an
CODE
ArrayBufferWriter<byte>
gives you raw bytes ready to send over WebSockets or TCP immediately!
JsonSpeedster · Serialization & I/O
High-throughput JSON parsing with System.Text.Json, Utf8Json...
The following users thanked JsonSpeedster for this post:
BytePusher
Memory & Performance
MEMBER
Rep: 209
Join Date: Dec 2025
Posts: 13
Thanks: 32
2y ago · Aug 25, 2023 3:47 PM
#2
Pairing
CODE
Utf8JsonWriter
with
CODE
ReadOnlySpan<byte>
property names (e.g.
CODE
writer.WriteString("user"u8, username)
using C# 11 UTF-8 string literals) eliminates even the string constant decoding step!
BytePusher · Memory & Performance
Zero-allocation C# code using Span<T>, Memory<T>, and Unsafe...
CSharpNinja
Senior .NET Developer
VIP
Rep: 329
Join Date: Jan 2020
Posts: 16
Thanks: 75
2y ago · Aug 25, 2023 7:47 PM
#3
UTF-8 string literals with the
CODE
"name"u8
suffix are so underrated. The compiler bakes the exact UTF-8 bytes directly into the binary assembly as a
CODE
ReadOnlySpan<byte>
.
CSharpNinja · Senior .NET Developer
C# enthusiast, building distributed backend services and hig...