71

What is the difference between string and StringBuilder?

Also, what would be some examples for understanding?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
ratty
  • 12,122
  • 29
  • 69
  • 105
  • 1
    possible duplicate of [String vs StringBuilder](http://stackoverflow.com/questions/73883/string-vs-stringbuilder) – George Stocker Jun 18 '10 at 13:21
  • And see also: http://stackoverflow.com/questions/919034/string-format-vs-string-string-or-stringbuilder http://stackoverflow.com/questions/665499/string-is-immutable-and-stringbuilder-is-mutable http://stackoverflow.com/questions/3069752/where-are-strings-more-useful-than-a-stringbuilder – George Stocker Jun 18 '10 at 13:22
  • 5
    @George: The first other question is actually fairly narrow and it even starts with "I already know the difference" – something this question specifically *asks*. – Joey Jun 18 '10 at 13:24
  • 1
    @George: I can't believe that didn't come up in the Related sidebar. – Bill the Lizard Jun 18 '10 at 13:25
  • @Bill: It got better after using the proper tags. even better after editing the title. – Joey Jun 18 '10 at 13:28
  • 1
    @Johannes: That is better. I agree that this isn't *exactly* the same as any of the other linked questions, but that could just be because this one is a bit vague. – Bill the Lizard Jun 18 '10 at 13:35

13 Answers13

108

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).

Joey
  • 316,376
  • 76
  • 642
  • 652
  • "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?? – AminM Jul 09 '13 at 14:01
  • 5
    @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. – Joey Jul 09 '13 at 15:21
10

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#

Community
  • 1
  • 1
Shamseer K
  • 4,104
  • 1
  • 21
  • 35
7

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Hans Olsson
  • 51,774
  • 14
  • 88
  • 111
4

String

A String instance is immutable, that is, 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 new instance.

Difference between String and StringBuilder

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ram
  • 489
  • 2
  • 11
2

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Palantir
  • 22,691
  • 9
  • 74
  • 84
2

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
  • 369,957
  • 201
  • 546
  • 842
1

Strings are immutable i.e if you change their value, the old value will be discarded and a new value is created on the heap, whereas in string builder we can modify the existing value without the new value being created.

So performance-wise String Builder is beneficial as we are needlessly not occupying more memory space.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
1

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Andrey
  • 56,384
  • 10
  • 111
  • 154
0

You can use the Clone method if you want to iterate through strings along with the string builder... It returns an object so you can convert to a string using the ToString method...:)

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
user2440156
  • 217
  • 2
  • 2
0

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 the overhead of instantiating a StringBuilder object it's said by Microsoft that it's useful to use when you have more than 5-10 string concatenations.

For sample code I suggest you take a look here:

Kris van der Mast
  • 15,905
  • 7
  • 35
  • 57
0

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 represents a mutable string. This class provides some useful methods that make the user able to manage the String wrapped by the StringBuilder. Notice that all the manipulations are made on the same StringBuilder instance.

Microsoft encourages the use of StringBuilder because it is more effective in terms of memory usage.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
AngeloBad
  • 1,983
  • 21
  • 42
0

Also the complexity of concatenations of String is O(N2), while for StringBuffer it is O(N).

So there might be performance problem where we use concatenations in loops as a lot of new objects are created each time.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Vinay Lodha
  • 1,997
  • 19
  • 29
0

System.String is a mutable object, meaning it cannot be modified after it’s been created. Please refer to Difference between string and StringBuilder in C#? for better understanding.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123