Improve StringBuilder usage by BrennanConroy · Pull Request #44691 · dotnet/aspnetcore (original) (raw)
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FYI @martincostello and @javiercn in regards to the conversation at https://github.com/dotnet/aspnetcore/pull/36368/files#r706039158
This makes use of Interpolated string handlers, and StringBuilder
has a custom one which allows formatting the interpolated string directly into it's internal buffer instead of instantiating a string then copying the string.
Method | Mean | Error | StdDev | Gen0 | Allocated |
---|---|---|---|---|---|
AppendToString | 748.7 ns | 12.33 ns | 10.93 ns | 0.1841 | 1448 B |
AppendInterpolated | 739.7 ns | 9.29 ns | 8.23 ns | 0.0620 | 488 B |
Benchmark code
[MemoryDiagnoser] public class AppendBenchmark { private byte[] _b = new byte[30];
[GlobalSetup]
public void Setup()
{
RandomNumberGenerator.Fill(_b);
}
[Benchmark]
public string AppendToString()
{
var sb = new StringBuilder();
foreach (var b in _b)
{
sb.Append(b.ToString("x2", CultureInfo.InvariantCulture));
}
return sb.ToString();
}
[Benchmark]
public string AppendInterpolated()
{
var sb = new StringBuilder();
foreach (var b in _b)
{
sb.Append(CultureInfo.InvariantCulture, $"{b:x2}");
}
return sb.ToString();
}
}