Skip to content

Commit

Permalink
Use pooled Utf8JsonWriter when doing sync streaming serialization. (d…
Browse files Browse the repository at this point in the history
…otnet#112745)

Co-authored-by: Stephen Toub <[email protected]>
  • Loading branch information
eiriktsarpalis and stephentoub authored Feb 21, 2025
1 parent 85b2455 commit 6e3e193
Showing 1 changed file with 24 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
Expand Down

0 comments on commit 6e3e193

Please sign in to comment.