Difference between string and StringBuilder in C#
Asked Answered
T

13

77

What is the difference between string and StringBuilder?

Also, what would be some examples for understanding?

Tallbot answered 18/6, 2010 at 12:9 Comment(6)
possible duplicate of String vs StringBuilderGide
And see also: #919534 #665999 #3070252Gide
@George: The first other question is actually fairly narrow and it even starts with "I already know the difference" – something this question specifically asks.Remembrance
@George: I can't believe that didn't come up in the Related sidebar.Masaryk
@Bill: It got better after using the proper tags. even better after editing the title.Remembrance
@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.Masaryk
R
113

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

Remembrance answered 18/6, 2010 at 12:13 Comment(2)
"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??Avidity
@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.Remembrance
M
13

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#

Machicolate answered 13/2, 2015 at 18:47 Comment(0)
T
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.

Telega answered 18/6, 2010 at 12:14 Comment(0)
B
6

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

Barytone answered 6/11, 2015 at 14:2 Comment(0)
O
3

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.

Obsolete answered 18/6, 2010 at 12:16 Comment(0)
A
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.

Aquiline answered 18/6, 2010 at 12:13 Comment(0)
M
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.

Masaryk answered 18/6, 2010 at 12:14 Comment(0)
P
2

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.

Proportionable answered 1/1, 2015 at 18:24 Comment(0)
E
1

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.

Evite answered 18/6, 2010 at 13:5 Comment(0)
S
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:

Shulock answered 18/6, 2010 at 12:16 Comment(0)
F
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.

Finkle answered 18/6, 2010 at 12:19 Comment(0)
B
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...:)

Bindery answered 12/7, 2013 at 4:38 Comment(0)
A
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.

Advisee answered 19/4, 2017 at 8:24 Comment(1)
please add some content from th elinkBefitting

© 2022 - 2024 — McMap. All rights reserved.