Avoid string.Concat(params string[]) in SimpleConsoleFormatter.CreateDefaultLogMessag...
authorStephen Toub <stoub@microsoft.com>
Wed, 18 Nov 2020 17:41:24 +0000 (12:41 -0500)
committerGitHub <noreply@github.com>
Wed, 18 Nov 2020 17:41:24 +0000 (12:41 -0500)
It's resulting in a string[] allocation and a string allocation, when we can instead just make a few more individual calls to Write and stackalloc the integer.

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

index bc702ca..1c790a4 100644 (file)
@@ -3,10 +3,6 @@
 
 using System;
 using System.IO;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-using System.Text;
 using Microsoft.Extensions.Logging.Abstractions;
 using Microsoft.Extensions.Options;
 
@@ -78,7 +74,19 @@ namespace Microsoft.Extensions.Logging.Console
             //       Request received
 
             // category and event id
-            textWriter.Write(LoglevelPadding + logEntry.Category + '[' + eventId + "]");
+            textWriter.Write(LoglevelPadding);
+            textWriter.Write(logEntry.Category);
+            textWriter.Write('[');
+
+#if NETCOREAPP
+            Span<char> span = stackalloc char[10];
+            if (eventId.TryFormat(span, out int charsWritten))
+                textWriter.Write(span.Slice(0, charsWritten));
+            else
+#endif
+                textWriter.Write(eventId.ToString());
+
+            textWriter.Write(']');
             if (!singleLine)
             {
                 textWriter.Write(Environment.NewLine);
@@ -177,7 +185,8 @@ namespace Microsoft.Extensions.Logging.Console
                     if (paddingNeeded)
                     {
                         paddingNeeded = false;
-                        state.Write(_messagePadding + "=> ");
+                        state.Write(_messagePadding);
+                        state.Write("=> ");
                     }
                     else
                     {