Skip to content

Commit

Permalink
Optimize memory allocations (dotnet#98702)
Browse files Browse the repository at this point in the history
  • Loading branch information
cd21h committed Mar 11, 2024
1 parent 71344ce commit 7b0968f
Showing 1 changed file with 14 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
#if NETCOREAPP
using System.Buffers;
#endif
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
Expand Down Expand Up @@ -76,7 +79,17 @@ public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeP
writer.Flush();
}
#if NETCOREAPP
textWriter.Write(Encoding.UTF8.GetString(output.WrittenMemory.Span));
var messageBytes = output.WrittenMemory.Span;
var logMessageBuffer = ArrayPool<char>.Shared.Rent(Encoding.UTF8.GetCharCount(messageBytes));
try
{
var charsWritten = Encoding.UTF8.GetChars(messageBytes, logMessageBuffer);
textWriter.Write(logMessageBuffer, 0, charsWritten);
}
finally
{
ArrayPool<char>.Shared.Return(logMessageBuffer);
}
#else
textWriter.Write(Encoding.UTF8.GetString(output.WrittenMemory.Span.ToArray()));
#endif
Expand Down

0 comments on commit 7b0968f

Please sign in to comment.