C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The number of strings that were appended was steadily increased to determine the slope of the graph.
Note: My test tried to defeat every compiler optimization by using different strings of the same lengths to append.
Result: The benchmark indicates that using the string reference type with Concat is faster for one to four strings inclusive.
Capacity: Using StringBuilder with an accurate capacity is always faster than without.
StringBuilder default code, red line: C#
StringBuilder builder1 = new StringBuilder();
for (int i = 1; i < count1; i++)
{
builder1.Append(s);
}
return builder1.ToString();
StringBuilder with capacity, purple line: C#
StringBuilder builder2 = new StringBuilder(count1 * maxLength);
for (int i = 1; i < count1; i++)
{
builder2.Append(s);
}
return builder2.ToString();
String concat, blue line: C#
string st1 = string.Empty;
for (int i = 1; i < count1; i++)
{
st1 += s;
}
return st1;
Warning: If your program is lightning fast 99% of the time, but fails 1% of the time, your program is unacceptable for important work.
Therefore: I think StringBuilder is preferable in most loops, unless you have studied the input to the loop.
But: It is clear to me that the trend of the lines would continue. I used capacity settings that were 100% accurate.
Capacity