From f51c7c52e81f302c746de921f5be9209900e01b2 Mon Sep 17 00:00:00 2001 From: Eirik Tsarpalis Date: Thu, 20 Feb 2025 15:53:32 +0000 Subject: [PATCH] Use pooled Utf8JsonWriter when doing sync streaming serialization. --- .../Metadata/JsonTypeInfoOfT.WriteHelpers.cs | 43 +++++++++++-------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.WriteHelpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.WriteHelpers.cs index f8f53f2d343e64..3a0e32900ad6e8 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.WriteHelpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.WriteHelpers.cs @@ -298,32 +298,37 @@ rootValue is not null && supportContinuation: true, supportAsync: false); - using var bufferWriter = new PooledByteBufferWriter(Options.DefaultBufferSize); - using var writer = new Utf8JsonWriter(bufferWriter, Options.GetWriterOptions()); - + Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(Options, out PooledByteBufferWriter bufferWriter); Debug.Assert(bufferWriter.CanGetUnflushedBytes); - state.PipeWriter = bufferWriter; - state.FlushThreshold = (int)(bufferWriter.Capacity * JsonSerializer.FlushThreshold); - - do + try { - isFinalBlock = EffectiveConverter.WriteCore(writer, rootValue, Options, ref state); - writer.Flush(); + state.PipeWriter = bufferWriter; + state.FlushThreshold = (int)(bufferWriter.Capacity * JsonSerializer.FlushThreshold); - bufferWriter.WriteToStream(utf8Json); - bufferWriter.Clear(); + do + { + isFinalBlock = EffectiveConverter.WriteCore(writer, rootValue, Options, ref state); + writer.Flush(); - Debug.Assert(state.PendingTask == null); - } while (!isFinalBlock); + bufferWriter.WriteToStream(utf8Json); + bufferWriter.Clear(); + + Debug.Assert(state.PendingTask == null); + } while (!isFinalBlock); - if (CanUseSerializeHandler) + if (CanUseSerializeHandler) + { + // On successful serialization, record the serialization size + // to determine potential suitability of the type for + // fast-path serialization in streaming methods. + Debug.Assert(writer.BytesPending == 0); + OnRootLevelAsyncSerializationCompleted(writer.BytesCommitted); + } + } + finally { - // On successful serialization, record the serialization size - // to determine potential suitability of the type for - // fast-path serialization in streaming methods. - Debug.Assert(writer.BytesPending == 0); - OnRootLevelAsyncSerializationCompleted(writer.BytesCommitted); + Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, bufferWriter); } } }