Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does StringBuilder use more memory than String concatenation?

Tags:

string

c#

I know the obvious performance advantage to using the StringBuilder is in C#, but what is the memory difference like?

Does the StringBuilder use more memory? and as a side note, what essentially does the stringbuilder do differently that makes it so much faster?

like image 255
caesay Avatar asked Nov 16 '10 03:11

caesay


1 Answers

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.

like image 138
Dan Tao Avatar answered Sep 20 '22 05:09

Dan Tao