views:

387

answers:

8

I'd like to know the difference between string and StringBuilder and also need some examples for understanding.

+11  A: 

A string instance is immutable. You cannot change it after it was created. Any operation that appears to change the string instead returns a new instance:

string foo = "Foo";
// returns a new string instance instead of changing the old one
string bar = foo.Replace('o', 'a');
string baz = foo + "bar"; // ditto here

Immutable objects have some nice properties, such as they can be used across threads without fearing synchronization problems or that you can simply hand out your private backing fields directly without fearing that someone changes objects they shouldn't be changing (see arrays or mutable lists, which often need to be copied before returning them if that's not desired). But when used carelessly they may create severe performance problems (as nearly anything – if you need an example from a language that prides itself on speed of execution then look at C's string manipulation functions).

When you need a mutable string, such as one you're contructing piece-wise or where you change lots of things, then you'll need a StringBuilder which is a buffer of characters that can be changed. This has, for the most part, performance implications. If you want a mutable string and instead do it with a normal string instance, then you'll end up with creating and destroying lots of objects unnecessarily, whereas a StringBuilder instance itself will change, negating the need for many new objects.

Simple example: The following will make many programmers cringe with pain:

string s = string.Empty;
for (i = 0; i < 1000; i++) {
  s += i.ToString() + " ";
}

You'll end up creating 2001 strings here, of which 2000 are thrown away. The same example using StringBuilder:

StringBuilder sb = new StringBuilder();
for (i = 0; i < 1000; i++) {
  sb.Append(i);
  sb.Append(' ');
}

This should place much less stress on the memory allocator :-)

It should be noted however, that the C# compiler is reasonably smart when it comes to strings. For example, the following line

string foo = "abc" + "def" + "efg" + "hij";

will be joined by the compiler, leaving only a single string at runtime. Similarly, lines such as

string foo = a + b + c + d + e + f;

will be rewritten to

string foo = string.Concat(a, b, c, d, e, f);

so you don't have to pay for five nonsensical concatenations which would be the naïve way of handling that. This won't save you in loops as above (unless the compiler unrolls the loop but I think only the JIT may actually do so and better don't bet on that).

Joey
One could wonder why strings are "stupid".. :)
Filip Ekberg
A: 

A StringBuilder will help you when you need to build strings in multiple steps.

Instead of doing this:

String x = "";
x += "first ";
x += "second ";
x += "third ";

you do

StringBuilder sb = new StringBuilder("");
sb.Append("first ");
sb.Append("second ");
sb.Append("third");
String x = sb.ToString();

the final effect is the same, but the StringBuilder will use less memory and will run faster. Instead of creating a new string which is the concatenation of the two, it will create the chunks separately, and only at the end it will unite them.

Palantir
+1  A: 

String is immutable, which means that when you create a string you can never change it, rather it will create a new string to store the new value, this can be inefficient if you need to change the value of a string variable a lot.

Stringbuilder can be used to simulate a mutable string so is good for when you need to change a string a lot.

ho1
+1  A: 

From the StringBuilder Class documentation:

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Bill the Lizard
A: 

Hi,

a String is an immutable type. This means that whenever you start concatenating strings with each other you're creating new strings each time. If you do so many times you end up with a lot of heap overhead and the risk of running out of memory.

A StringBuilder instance is used to be able to append strings to the same instance, creating a string when you call the ToString method on it.

Due to overhead of instantiating a StringBuilder object it's said by Microsoft that it's usefull to use when you have more than 5-10 string concatenations.

For sample code I suggest you take a look here:

http://msdn.microsoft.com/en-us/library/system.string.aspx http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

http://msdn.microsoft.com/en-us/library/2839d5h5(VS.71).aspx

Grz, Kris.

XIII
A: 

Major difference:

String is immutable. It means that you can't modify string at all, the result of modification is new string. This is not effective if you plan to append to string

StringBuilder is mutable. It can be modified in any way and it doesn't require creation of new instance. When work is done, ToString() can be called to get the string.

Strings can participate in interning, it means that strings with same contents may have same addresses. StringBuilder can't be interned.

String is the only class that can have reference literal.

Andrey
A: 

A String (System.String) is a type defined inside the .NET framework. The String class is not mutable. This means that every time you do an action to an System.String instance, the .NET compiler create a new instance of the string. This operation is hidden to the developer.

A System.Text.StringBuilder is class that represent a mutable string. This class provide some useful method that make the user able to manage the String wrapped by the StringBuilder. Notice that all the manipulation are made on the same StringBuilder instance.

Microsoft encourage the use of StringBuilder cause of is more effective in term of memory usage.

Angelodev
A: 

Also complexity of concatenations of String is O(N2) while for StringBuffer is O(N). So There might be performance problem where we use concatenations in loops as lot of new objects created each time.

VinAy