Difference Between String and Stringbuilder in C#

Difference between string and StringBuilder in C#

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

What is the difference bewteen the string and string builder in c#

StringBuilder is mutable which gives better performance when you need to manipulate content multiple times.

In case of string, it has to create instances multiple times because string is immutable.

String vs. StringBuilder

Yes, the performance difference is significant. See the KB article "How to improve string concatenation performance in Visual C#".

I have always tried to code for clarity first, and then optimize for performance later. That's much easier than doing it the other way around! However, having seen the enormous performance difference in my applications between the two, I now think about it a little more carefully.

Luckily, it's relatively straightforward to run performance analysis on your code to see where you're spending the time, and then to modify it to use StringBuilder where needed.

What is the difference between string and StringBuilder?

Since both are reference types, why do they have different results?

Because string objects are highly optimized. In particular, since they're immutable, they can be interned by the compiler to prevent duplication.

If you have two different string objects that both represent the exact same string of characters (as in your example), the compiler will recognize that and maintain only one instance of the actual string object.

The result is that both the s1 and s2 objects actually are the same object as far as the compiler is concerned and even reference the same location in memory.

This bookkeeping happens behind the scenes in something called an "intern table", but that's not really something you need to worry yourself with. The important thing is that all string literals are interned by default by the compiler.

The same kind of thing does not happen for StringBuilder objects, because they are not immutable. They're designed to allow you to modify a string object, and as such, the optimizations don't make much sense. That's why your sb1 and sb2 objects are actually seen as two different objects.

The rule of thumb is quite simple: Use string by default, or when you want a single immutable string of characters. Only use StringBuilder when you want to modify the same string multiple times, say in a loop or other relatively short section of code.

Relevant reading: Optimizing C# String Performance

Where are strings more useful than a StringBuilder?

It's not a case of which is more useful...

A String is a String - one or more characters next to eachother. If you want to change a string in someway, it will simply create more strings because they are immutable.

A StringBuilder is a class which creates strings. It provides a means of constructing them without creating lots of reduntant strings in memory. The end result will always be a String.

Don't do this

string s = "my string";
s += " is now a little longer";

or

s = s + " is now longer again";

That would create 5 strings in memory (in reality, see below).

Do this:

StringBuilder sb = new StringBuilder();
sb.Append("my string");
sb.Append(" is now a little longer");
sb.Append(" is now longer again");
string s = sb.ToString();

That would create 1 string in memory (again, see below).

You can do this:

string s = "It is now " + DateTime.Now + ".";

This only creates 1 string in memory.

As a side-note, creating a StringBuilder does take a certain amount of memory anyway. As a rough rule of thumb:

  • Always use a StringBuilder if you're concatenating strings in a loop.
  • Use a StringBuilder if you're concatenating a string more than 4 times.

.net how to compare a stringbuilder to a string

The simplest way is to get the content of the StringBuilder as a string:

If sb.ToString() = s Then ...

If you want to avoid creating that string (perhaps for memory usage concerns), I am afraid that you have to write your own routine to compare them. Basically something like:

Public Shared Function SbEquals(sb As StringBuilder, s As String) As Boolean
If sb.Length <> s.Length Then Return False
For i As Integer = 0 to s.Length - 1
If sb(i) <> s(i) Return False
Next
Return True
End Function

C# How StringBuilder is mutable?

Mutable doesn't mean that it can't create new stuff. Mutable just means that its state can change after the constructor returns.

For example, this is mutable, even though string is immutable:

class Foo {
public string Bar { get; set; }

public void FooMethod() {
Bar = new string('!', 10);
}
}

Because we can change the state of it by setting Bar or calling FooMethod:

 someFoo.FooMethod();

Yes, I am creating a new string here in the FooMethod, but that does not matter. What does matter is that Bar now has a new value! The state of someFoo changed.

We say StringBuilder is mutable because its state can change, without creating a new StringBuilder. As you have looked up, StringBuilder stores a char array. Each time you append something, that char array changes to something else, but no new StringBuilders are created. This is solid proof that StringBuilder is mutable.

Difference between StringBuilder and StringBuffer

StringBuffer is synchronized, StringBuilder is not.



Related Topics



Leave a reply



Submit