Benchmarks
as a .NET developer , most of the time I have gotten stuck in my routine works like solving bugs or writings new modules but I have decided to allocate specific time every week and search and code new features of .NET. also i want to benchmark every subject that is important but it has had less issue in the apps that i have developed.
<PackageReference Include="BenchmarkDotNet" Version="0.14.0" />
<TargetFramework>net9.0</TargetFramework>
1) string concatenation with StringBuilder
I have written many programs that I had to use string concatenation but because of the size of those programs, it was not a big deal to concatenate strings in simple method with just using + operator or using StringBuilder object. but I have studied many articles about the benefits of StringBuilder especially memory usage. so, I designed a simple benchmark to concatenate 1000 words with different length and compared the memory usage and execution time.
This is my simple benchmark code:
MemoryDiagnoser(true)]
[MaxIterationCount(2000)]
[InvocationCount(100)]
[WarmupCount(100)]
public class BenchmarkStringBuilder{
string[] words;
public BenchmarkStringBuilder(){
words=File.ReadAllLines(@"D:\Projects\TestParamCollection\Tests\Resources\Words.txt");
}
[Benchmark]
public bool CreateParagraphSimple(){
string para="";
for(int i=0;i<words.Length;i++)
{
para+=" "+words[i];
}
return true;
}
[Benchmark]
public bool CreateParagraphWithStringBuilder(){
StringBuilder para=new StringBuilder();
for(int i=0;i<words.Length;i++)
{
para.Append(" "+words[i]);
}
return true;
}
}
Result:
It is completely obvious that using StringBuilder is so better especially when we want to concatenate huge number of words.
领英推荐
CreateParagraphSimple
CreateParagraphWithStringBuilder
Explanation:
CreateParagraphSimple
CreateParagraphWithStringBuilder
Conclusion: