Created
July 9, 2023 13:44
-
-
Save bellons91/6c03de94853a75e5520077360009bb6b to your computer and use it in GitHub Desktop.
String concat vs StringBuilder
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
#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