Skip to content

Commit

Permalink
Reuse StringBuilders in EventArgsFormatting
Browse files Browse the repository at this point in the history
While I was editing in this area I noticed that the calling pattern
around StringBuilders in FormatEventMessage looked allocatey.

Instead of creating two throwaway StringBuilders to format a single
message,

1. Grab a ReusableStringBuilder
2. Reuse the builder between "construct format string" and "get final
   message".

We chose ReusableStringBuilder over StringBuilderCache because logging
sometimes creates strings that are _much_ larger than the 512 character
limit of SBC. That also reduces the need to prereserve a size: the
process-wide pool's elements should be pretty big already.

See dotnet#2697 (comment)
for stats on string length.
  • Loading branch information
rainersigwald committed Jan 18, 2022
1 parent de78f7f commit a7460af
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Shared/EventArgsFormatting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,9 @@ internal static string FormatEventMessage
string logOutputProperties
)
{
StringBuilder format = new StringBuilder();
// capacity is the longest possible path through the below
// to avoid reallocating while constructing the string
using ReuseableStringBuilder format = new(51);

// Uncomment these lines to show show the processor, if present.
/*
Expand Down Expand Up @@ -328,9 +330,11 @@ string logOutputProperties

string finalFormat = format.ToString();

// Reuse the string builder to create the final message
ReuseableStringBuilder formattedMessage = format.Clear();

// If there are multiple lines, show each line as a separate message.
string[] lines = SplitStringOnNewLines(message);
StringBuilder formattedMessage = new StringBuilder();

for (int i = 0; i < lines.Length; i++)
{
Expand Down

0 comments on commit a7460af

Please sign in to comment.