-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
Background and motivation
Currently, Utf8JsonWriter does not expose a public method to reset its state and reuse the same writer instance across multiple serialization operations with different buffers and writer options. The only way to reuse a Utf8JsonWriter is to fully dispose it and create a new instance. This can be inefficient in scenarios (such as high-performance or thread-local pools) that aim to reduce allocations by reusing objects and buffers.
This limitation affects any component building on top of System.Text.Json that needs to optimize serialization performance. Libraries implementing custom serializers, JSON-based protocols, or high-throughput APIs often need to pool Utf8JsonWriter instances to minimize GC pressure. Without a public Reset method that accepts both a buffer and options, developers are forced to use workarounds such as UnsafeAccessor (on .NET) or reflection (on older frameworks) to call the internal method:
[UnsafeAccessor(UnsafeAccessorKind. Method, Name = "Reset")]
public static extern void Reset(this Utf8JsonWriter writer, IBufferWriter<byte> bufferWriter, JsonWriterOptions options);These workarounds are brittle and rely on implementation details that could change. Exposing a public Reset method would greatly improve usability and performance for pooling scenarios while eliminating the need for unsafe reflection hacks.
API Proposal
namespace System.Text. Json;
public sealed partial class Utf8JsonWriter : IDisposable, IAsyncDisposable
{
// Existing overloads:
// public void Reset();
// public void Reset(IBufferWriter<byte> bufferWriter);
// public void Reset(Stream utf8Json);
public void Reset(IBufferWriter<byte> bufferWriter, JsonWriterOptions options);
public void Reset(Stream utf8Json, JsonWriterOptions options);
}API Usage
// Pooling scenario example
var bufferWriter = new ArrayBufferWriter<byte>(capacity: 1024);
var writer = GetPooledUtf8JsonWriter();
writer.Reset(bufferWriter, new JsonWriterOptions { Indented = true });
JsonSerializer. Serialize(writer, value, value.GetType(), options);
ReturnPooledUtf8JsonWriter(writer);
// This avoids repeated allocations and allows reuse of writer instances and buffers. Alternative Designs
Alternatives include re-creating Utf8JsonWriter per serialization, but this has higher allocation and GC impact. Another alternative is to expose only a Reset method for the buffer but not writer options, though this restricts configurability and could be less flexible for pooling scenarios.
Risks
No response