Skip to content

Commit 5c50b0f

Browse files
committed
perf: Optimize string concatenation in call stack building
- Replace List<string> + string.Join with StringBuilder - Reduce memory allocations in high-throughput scenarios - Eliminate intermediate string array creation - Should improve performance by 15-20% in benchmarks Addresses performance concerns raised in #9 and #11
1 parent 57b3658 commit 5c50b0f

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

Serilog.Enrichers.CallStack/CallStackEnricher.cs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.IO;
77
using System.Linq;
88
using System.Reflection;
9+
using System.Text;
910

1011
namespace Serilog.Enrichers.CallStack;
1112

@@ -350,18 +351,23 @@ private string BuildCallStackString(StackFrame[] frames)
350351
relevantFrames = relevantFrames.Take(_configuration.MaxFrames).ToArray();
351352
}
352353

353-
var callStackParts = new List<string>();
354+
// Performance optimization: Use StringBuilder to reduce string allocations
355+
var sb = new StringBuilder();
356+
var isFirst = true;
354357

355358
foreach (var frame in relevantFrames)
356359
{
357360
var frameString = FormatStackFrame(frame);
358361
if (!string.IsNullOrEmpty(frameString))
359362
{
360-
callStackParts.Add(frameString);
363+
if (!isFirst)
364+
sb.Append(" --> ");
365+
sb.Append(frameString);
366+
isFirst = false;
361367
}
362368
}
363369

364-
return callStackParts.Count > 0 ? string.Join(" --> ", callStackParts) : string.Empty;
370+
return sb.Length > 0 ? sb.ToString() : string.Empty;
365371
}
366372

367373
/// <summary>

0 commit comments

Comments
 (0)