StringBuilder
is more efficient than string concatenation because string concatenation creates a new immutable string each time you use it, while the string builder creates a single buffer for appending characters to. This page in the C# doc states that the String object is immutable and the StringBuilder object is dynamic. It also states
When you modify the StringBuilder, it does not reallocate size for itself until the capacity is reached. When this occurs, the new space is allocated automatically and the capacity is doubled. You can specify the capacity of the StringBuilder class using one of the overloaded constructors.
However, according to this article, string.Join()
has the best algorithm for appending characters to a string.
According to this page in the Java documentation, String
s are immutable, while StringBuilder
s are essentially the same, but can be changed.
It appears that using string concatenation results in the overhead of creating a new immutable string, while using a string builder just results in characters being appended to a buffer. Creating and initializing a new object is more expensive than appending a character to an buffer, so that is why string builder is faster, as a general rule, than string concatenation.