String vs. StringBuilder

2018-12-31 08:24发布

I understand the difference between String and StringBuilder (StringBuilder being mutable) but is there a large performance difference between the two?

The program I’m working on has a lot of case driven string appends (500+). Is using StringBuilder a better choice?

25条回答
君临天下
2楼-- · 2018-12-31 08:46

String Vs String Builder:

First thing you have to know that In which assembly these two classes lives?

So,

string is present in System namespace.

and

StringBuilder is present in System.Text namespace.

For string declaration:

You have to include the System namespace. something like this. Using System;

and

For StringBuilder declaration:

You have to include the System.text namespace. something like this. Using System.text;

Now Come the the actual Question.

What is the differene between string & StringBuilder?

The main difference between these two is that:

string is immutable.

and

StringBuilder is mutable.

So Now lets discuss the difference between immutable and mutable

Mutable: : means Changable.

Immutable: : means Not Changable.

For example:

using System;

namespace StringVsStrigBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            // String Example

            string name = "Rehan";
            name = name + "Shah";
            name = name + "RS";
            name = name + "---";
            name = name + "I love to write programs.";

            // Now when I run this program this output will be look like this.
            // output : "Rehan Shah RS --- I love to write programs."
        }
    }
}

So in this case we are going to changing same object 5-times.

So the Obvious question is that ! What is actually happen under the hood, when we change the same string 5-times.

This is What Happen when we change the same string 5-times.

let look at the figure.

enter image description here

Explaination:

When we first initialize this variable "name" to "Rehan" i-e string name = "Rehan" this variable get created on stack "name" and pointing to that "Rehan" value. after this line is executed: "name = name + "Shah". the reference variable is no longer pointing to that object "Rehan" it now pointing to "Shah" and so on.

So string is immutable meaning that once we create the object in the memory we can't change them.

So when we concatinating the name variable the previous object remains there in the memory and another new string object is get created...

So from the above figure we have five-objects the four-objects are thrown away they are not used at all. They stil remain in memory and they occuy the amount of memory. "Garbage Collector" is responsible for that so clean that resources from the memory.

So in case of string anytime when we manipulate the string over and over again we have some many objects Created ans stay there at in the memory.

So this is the story of string Variable.

Now Let's look at toward StringBuilder Object. For Example:

using System;
using System.Text;

namespace StringVsStrigBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            // StringBuilder Example

            StringBuilder name = new StringBuilder();
            name.Append("Rehan");
            name.Append("Shah");
            name.Append("RS");
            name.Append("---");
            name.Append("I love to write programs.");


            // Now when I run this program this output will be look like this.
            // output : "Rehan Shah Rs --- I love to write programs."
        }
    }
}

So in this case we are going to changing same object 5-times.

So the Obvious question is that ! What is actually happen under the hood, when we change the same StringBuilder 5-times.

This is What Happen when we change the same StringBuilder 5-times.

let look at the figure. enter image description here

Explaination: In case of StringBuilder object. you wouldn't get the new object. The same object will be change in memory so even if you change the object et say 10,000 times we will still have only one stringBuilder object.

You don't have alot of garbage objects or non_referenced stringBuilder objects because why it can be change. It is mutable meaning it change over a time?

Differences:

  • String is present in System namespace where as Stringbuilder present in System.Text namespace.
  • string is immutable where as StringBuilder is mutabe.
查看更多
长期被迫恋爱
3楼-- · 2018-12-31 08:47

Don't blindly go for StringBuilder. There are scenarios where StringBuilder does not improve the performance.

Rico Mariani has written two insightful blog entries on this:

http://blogs.msdn.com/ricom/archive/2003/12/02/40778.aspx

http://blogs.msdn.com/ricom/archive/2003/12/15/43628.aspx

查看更多
倾城一夜雪
4楼-- · 2018-12-31 08:51

StringBuilder reduces the number of allocations and assignments, at a cost of extra memory used. Used properly, it can completely remove the need for the compiler to allocate larger and larger strings over and over until the result is found.

string result = "";
for(int i = 0; i != N; ++i)
{
   result = result + i.ToString();   // allocates a new string, then assigns it to result, which gets repeated N times
}

vs.

String result;
StringBuilder sb = new StringBuilder(10000);   // create a buffer of 10k
for(int i = 0; i != N; ++i)
{
   sb.Append(i.ToString());          // fill the buffer, resizing if it overflows the buffer
}

result = sb.ToString();   // assigns once
查看更多
与风俱净
5楼-- · 2018-12-31 08:52

A simple example to demonstrate the difference in speed when using String concatenation vs StringBuilder:

System.Diagnostics.Stopwatch time = new Stopwatch();
string test = string.Empty;
time.Start();
for (int i = 0; i < 100000; i++)
{
    test += i;
}
time.Stop();
System.Console.WriteLine("Using String concatenation: " + time.ElapsedMilliseconds + " milliseconds");

Result:

Using String concatenation: 15423 milliseconds

StringBuilder test1 = new StringBuilder();
time.Reset();
time.Start();
for (int i = 0; i < 100000; i++)
{
    test1.Append(i);
}
time.Stop();
System.Console.WriteLine("Using StringBuilder: " + time.ElapsedMilliseconds + " milliseconds");

Result:

Using StringBuilder: 10 milliseconds

As a result, the first iteration took 15423 ms while the second iteration using StringBuilder took 10 ms.

It looks to me that using StringBuilder is faster, a lot faster.

查看更多
孤独寂梦人
6楼-- · 2018-12-31 08:52

Yes, StringBuilder gives better performance while performing repeated operation over a string. It is because all the changes are made to a single instance so it can save a lot of time instead of creating a new instance like String.

String Vs Stringbuilder

  • String

    1. under System namespace
    2. immutable (read-only) instance
    3. performance degrades when continuous change of value occures
    4. thread safe
  • StringBuilder (mutable string)

    1. under System.Text namespace
    2. mutable instance
    3. shows better performance since new changes are made to existing instance

Strongly recommend dotnet mob article : String Vs StringBuilder in C#.

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

查看更多
初与友歌
7楼-- · 2018-12-31 08:52

Further to the previous answers, the first thing I always do when thinking of issues like this is to create a small test application. Inside this app, perform some timing test for both scenarios and see for yourself which is quicker.

IMHO, appending 500+ string entries should definitely use StringBuilder.

查看更多
登录 后发表回答