Skip to content

Commit f0ee416

Browse files
cd21htarekgh
andauthored
Optimize memory allocations (dotnet#98702) (dotnet#99542)
* Optimize memory allocations (dotnet#98702) * Use `UTF8.GetMaxCharCount` * Optimize memory allocations (dotnet#98702) * Use `UTF8.GetMaxCharCount` * Optimize netfx/netstandard 2.0 cases too * Fix formatting * Fix build error --------- Co-authored-by: Tarek Mahmoud Sayed <tarekms@microsoft.com>
1 parent 1ee61b8 commit f0ee416

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
using System;
5+
using System.Buffers;
56
using System.Collections.Generic;
67
using System.Diagnostics.CodeAnalysis;
78
using System.Globalization;
@@ -81,11 +82,30 @@ private void WriteInternal(IExternalScopeProvider? scopeProvider, TextWriter tex
8182
writer.WriteEndObject();
8283
writer.Flush();
8384
}
84-
#if NET
85-
textWriter.Write(Encoding.UTF8.GetString(output.WrittenMemory.Span));
86-
#else
87-
textWriter.Write(Encoding.UTF8.GetString(output.WrittenMemory.Span.ToArray()));
88-
#endif
85+
86+
var messageBytes = output.WrittenMemory.Span;
87+
var logMessageBuffer = ArrayPool<char>.Shared.Rent(Encoding.UTF8.GetMaxCharCount(messageBytes.Length));
88+
try
89+
{
90+
#if NET
91+
var charsWritten = Encoding.UTF8.GetChars(messageBytes, logMessageBuffer);
92+
#else
93+
int charsWritten;
94+
unsafe
95+
{
96+
fixed (byte* messageBytesPtr = messageBytes)
97+
fixed (char* logMessageBufferPtr = logMessageBuffer)
98+
{
99+
charsWritten = Encoding.UTF8.GetChars(messageBytesPtr, messageBytes.Length, logMessageBufferPtr, logMessageBuffer.Length);
100+
}
101+
}
102+
#endif
103+
textWriter.Write(logMessageBuffer, 0, charsWritten);
104+
}
105+
finally
106+
{
107+
ArrayPool<char>.Shared.Return(logMessageBuffer);
108+
}
89109
}
90110
textWriter.Write(Environment.NewLine);
91111
}

0 commit comments

Comments
 (0)