2y ago · Aug 25, 2023 2:10 PM
Standard produces a , 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:
Combining with an gives you raw bytes ready to send over WebSockets or TCP immediately!
CODE
JsonSerializer.Serialize() CODE
stringHow 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 CODE
ArrayBufferWriter<byte>
JsonSpeedster · Serialization & I/O
High-throughput JSON parsing with System.Text.Json, Utf8Json...
High-throughput JSON parsing with System.Text.Json, Utf8Json...
The following users thanked JsonSpeedster for this post: