The Microsoft Developer Network has a great comparison:
Although StringBuilder and String both represent sequences of
characters, they are implemented differently. String is an immutable
type. That is, each operation that appears to modify a String object
actually creates a new string.For example, the call to the String.Concat method in the following C#
example appears to change the value of a string variable named value.
In fact, the Concat method returns a value object that has a different
value and address from the value object that was passed to the method.
Note that the example must be compiled using the /unsafe compiler
option. For routines that perform extensive string manipulation (such
as apps that modify a string numerous times in a loop), modifying a
string repeatedly can exact a significant performance penalty. The
alternative is to use StringBuilder, which is a mutable string class.
Mutability means that once an instance of the class has been created,
it can be modified by appending, removing, replacing, or inserting
characters. A StringBuilder object maintains a buffer to accommodate
expansions to the string. New data is appended to the buffer if room
is available; otherwise, a new, larger buffer is allocated, data from
the original buffer is copied to the new buffer, and the new data is
then appended to the new buffer.
The recommended usage for a String
is:
-
When the number of changes that your application will make to a string are quite small. In these instances
StringBuilder
may offer negligible or no performance improvement overString
. (Due to the way theStringBuilder
handles its buffer) -
When you are performing a fix number of concatenation operations, particularly with
String
literals. The Compiler should combine these into one single operation. -
When you have to perform extensive search operations while you are building a
String
.StringBuilder
lacks search methods such asIndexOf
orStartsWith
. You’ll have to convert yourStringBuilder
object to aString
for these operations which may negate the performance.
The recommended usage for StringBuilder
:
-
When you expect your application to make unknown number of changes to a string at design time (an example would be loops/random number strings).
-
When you expect your application to make significant changes to a
string
.
So the question really shouldn’t be, “Which performs better”, it should be “Under which circumstance is one more ideal than another?”
solved How Much Faster is StringBuilder respect of concat operator + in C# .Net [duplicate]