Skip to content

Commit

Permalink
Optimize memory allocations (#98702) (#99542)
Browse files Browse the repository at this point in the history
* Optimize memory allocations (#98702)

* Use `UTF8.GetMaxCharCount`

* Optimize memory allocations (#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>
  • Loading branch information
cd21h and tarekgh authored May 15, 2024
1 parent 1ee61b8 commit f0ee416
Showing 1 changed file with 25 additions and 5 deletions.
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

0 comments on commit f0ee416

Please sign in to comment.