Skip to content

Optimize memory allocations (#98702) #99542

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
May 15, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
Expand Down Expand Up @@ -81,11 +82,30 @@ private void WriteInternal(IExternalScopeProvider? scopeProvider, TextWriter tex
writer.WriteEndObject();
writer.Flush();
}
#if NET
textWriter.Write(Encoding.UTF8.GetString(output.WrittenMemory.Span));
#else
textWriter.Write(Encoding.UTF8.GetString(output.WrittenMemory.Span.ToArray()));
#endif

var messageBytes = output.WrittenMemory.Span;
var logMessageBuffer = ArrayPool<char>.Shared.Rent(Encoding.UTF8.GetMaxCharCount(messageBytes.Length));
try
{
#if NET
var charsWritten = Encoding.UTF8.GetChars(messageBytes, logMessageBuffer);
#else
int charsWritten;
unsafe
{
fixed (byte* messageBytesPtr = messageBytes)
fixed (char* logMessageBufferPtr = logMessageBuffer)
{
charsWritten = Encoding.UTF8.GetChars(messageBytesPtr, messageBytes.Length, logMessageBufferPtr, logMessageBuffer.Length);
}
}
#endif
textWriter.Write(logMessageBuffer, 0, charsWritten);
}
finally
{
ArrayPool<char>.Shared.Return(logMessageBuffer);
}
}
textWriter.Write(Environment.NewLine);
}
Expand Down
Loading