Does StringBuilder use more memory than String concatenation?

Solution 1:

Short answer: StringBuilder is appropriate in cases where you are concatenating an arbitrary number of strings, which you don't know at compile time.

If you do know what strings you're combining at compile time, StringBuilder is basically pointless as you don't need its dynamic resizing capabilities.

Example 1: You want to combine "cat", "dog", and "mouse". This is exactly 11 characters. You could simply allocate a char[] array of length 11 and fill it with the characters from these strings. This is essentially what string.Concat does.

Example 2: You want to join an unspecified number of user-supplied strings into a single string. Since the amount of data to concatenate is unknown in advance, using a StringBuilder is appropriate in this case.

Solution 2:

StringBuilder is not necessarily faster. As I recall, if you're concatentating fewer than a dozen strings, string concatentation (eiether via String.Concat or simple str1 + str2) is actually faster. The reason is that allocation and initialization of StringBuilder actually takes time.

The reason that StringBuilder is faster is that it creates an internal buffer that it adds strings to. If you are concatenating 20 strings, StringBuilder simply appends one after another to its buffer and finally returns the result when requested - via its ToString() method. (I'm assuming there is sufficient buffer space. Otherwise StringBuilder worries about re-allocating the buffer and has heuristics for helping it not re-allocate too many times.) If you were concatentating strings, each string concat would allocate a new string of length (str1.Length + str2.Length) and copy the first and second string into place. This results in a lot of re-copying of strings.

var result = str1 + str2 + str3 + ... + strN;

This will require N-1 allocations and N-1 copy operations. This can get very expensive for large N. Plus note that you're copying the contents of str1 N-1 times. Once to get the result of str1+str2. Then again to get the result of (str1+str2)+str3. With StringBuilder, each string is copied into the internal buffer only once, assuming the buffer is sufficiently large to hold the individual strings.

Solution 3:

I think you really should read this: The Sad Tragedy of Micro-Optimization Theater, your answer of StringBuilder v/s Concat , after the jump