Created
January 14, 2023 14:12
-
-
Save davepcallan/fa0cebae7381c65f40588e42eb1c01f6 to your computer and use it in GitHub Desktop.
Concat 50K one char strings with + and StringBuilder in .NET 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
helloago