Difference between string and StringBuilder in C#

160,513

Solution 1

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, 2000 of which 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).

Solution 2

String vs. StringBuilder

  • String

    • Under System namespace

    • Immutable (readonly) instance

    • Performance degrades when continuous change of value occurs

    • Thread-safe

  • StringBuilder (mutable string)

    1. Under System.Text namespace
    2. Mutable instance
    3. Shows better performance since new changes are made to an existing instance

For a descriptive article about this topic with a lot of examples using ObjectIDGenerator, follow this link.

Related Stack Overflow question: Mutability of string when string doesn't change in C#

Solution 3

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, and 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 it is good for when you need to change a string a lot.

Solution 4

String

A String instance is immutable, which means, we cannot change it after it was created. If we perform any operation on a String it will return a new instance (creates a new instance in memory) instead of modifying the existing instance value.

StringBuilder

StringBuilder is mutable, that is, if we perform any operation on StringBuilder it will update the existing instance value and it will not create a new instance.

Difference between String and StringBuilder

Solution 5

Major difference:

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

StringBuilder is mutable. It can be modified in any way and it doesn't require creation of a new instance. When the 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 a reference literal.

Share:
160,513
ratty
Author by

ratty

I Am Software developer from india.I am working as software developer in C#.net for past 1 Year .Contact me thorugh [email protected].

Updated on July 05, 2022

Comments

  • ratty
    ratty almost 2 years

    What is the difference between string and StringBuilder?

    Also, what would be some examples for understanding?

  • AminM
    AminM almost 11 years
    "Any operation that appears to change the string instead returns a new instance" but why?? what is reason?? why string is not Mutable ?? why CLR create new instance and delete Previous instance??
  • Rich
    Rich almost 11 years
    @Jeson: Immutable data structures have a lot of nice properties, most of them related to writing safer code by default. You don't have to worry about your strings changing just because another thread works on them. And you don't have to return copies of a class' internal strings to prevent consumers from tampering with your fields.
  • Robert
    Robert about 7 years
    please add some content from th elink