Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Created January 14, 2023 14:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Concat 50K one char strings with + and StringBuilder in .NET 7
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Reports;
namespace BenchmarkDotNet.Samples
{
[Config(typeof(Config))]
[SimpleJob(RuntimeMoniker.Net70)]
[MemoryDiagnoser]
[HideColumns(Column.RatioSD, Column.AllocRatio, Column.Error, Column.StdDev)]
public class StringConcatInLoop
{
[Params(50, 50000)]
public int Total { get; set; }
[Benchmark(Baseline = true)]
public string Plus()
{
var result = string.Empty;
for (int i = 0; i < Total; i++)
{
result = result + '*';
}
return result;
}
[Benchmark]
public string SB()
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < Total; i++)
{
result.Append('*');
}
return result.ToString();
}
private class Config : ManualConfig
{
public Config()
{
SummaryStyle =
SummaryStyle.Default.WithRatioStyle(RatioStyle.Percentage)
.WithTimeUnit(Perfolizer.Horology.TimeUnit.Millisecond);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment