Skip to content

Instantly share code, notes, and snippets.

@bellons91
Created July 9, 2023 13:44
Show Gist options
  • Save bellons91/6c03de94853a75e5520077360009bb6b to your computer and use it in GitHub Desktop.
Save bellons91/6c03de94853a75e5520077360009bb6b to your computer and use it in GitHub Desktop.
String concat vs StringBuilder
#LINQPad optimize+
void Main()
{
var summary = BenchmarkRunner.Run<StringConcatenationPerformance>();
}
[MemoryDiagnoser]
public class StringConcatenationPerformance
{
[Params(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)]
public int StringsCount;
public string[] items;
[Benchmark]
public void UseAppend()
{
items = Enumerable.Range(0, StringsCount).Select(_ => _.ToString()).ToArray();
string value = "";
foreach (var item in items)
{
value += item;
}
}
[Benchmark]
public void UseConcat()
{
items = Enumerable.Range(0, StringsCount).Select(_ => _.ToString()).ToArray();
string value = "";
foreach (var item in items)
{
value = string.Concat(value, item);
}
}
[Benchmark]
public void UseStringBuilder()
{
items = Enumerable.Range(0, StringsCount).Select(_ => _.ToString()).ToArray();
string value = "";
StringBuilder sb = new StringBuilder();
foreach (var item in items)
{
sb.Append(item);
}
value = sb.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment