Possible Duplicates:
When to use StringBuilder?
string is immutable and stringbuilder is mutable
what is diffrent of string and string builder ? where do we use string builder ?
Possible Duplicates:
When to use StringBuilder?
string is immutable and stringbuilder is mutable
what is diffrent of string and string builder ? where do we use string builder ?
The main difference is that a StringBuilder is mutable (meaning that it can be modified), whereas a string is immutable (meaning that once it is constructed it cannot be modified).
This difference is important for example if you are trying to create a large string from lots of smaller strings. If you use a StringBuilder you append the strings without creating a new object, giving O(n) performance. If you use strings you create lots of intermediate strings which are immediately discarded, but all the extra copying means that it becomes an O(n2) operation.
Example code showing the usage of each for contructing a large string from many smaller strings:
String
string s = "";
for (int i = 0; i < 10000; ++i)
{
s += "foo";
}
StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; ++i)
{
sb.Append("foo");
}
string s = sb.ToString();
Aside from string being immutable and stringbuilder being mutable, you should use a string builder when you are going to be doing a lot of string concatenation, as that is a very expensive operation, especially when contained in a loop.