4

Can you explain to me why using StringBuilder works much faster than just adding strings with "+" every time? For example:

for (int i = 0; i < arr.length; i++) {
    stringBuilder.append(arr[i]);
}
str = stringBuilder.toString();

Is much faster than:

for (int i = 0; i < arr.length; i++) {
    str = str + arr[i];
}

Why is this happening?

J.Selva
  • 171
  • 1
  • 14
Dan Barnet
  • 77
  • 1
  • 4
  • That's not a duplicate... – Dan Barnet Aug 22 '15 at 16:41
  • 1
    `toString()` rather than `ToString()` makes me think this is java, not C#. In any case, please correct your tags for the language you are describing. `StringBuilder` is a class, and may have different implementations, rendering some answers potentially invalid. – Rob Aug 22 '15 at 16:54
  • If this is a Java String question, my understanding was that String concatenation is "faster" with the + operator because the JDK/JVM optimises for the most efficient approach, the last time I looked it was suggested that it would use StringBuilder under the hood. It was suggested that unless you are concatenating in a loop you should use the +. Admittedly this was back in JDK 5. – Gavin Aug 22 '15 at 17:51

1 Answers1

8

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, Strings are immutable, while StringBuilders 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.