I understand the difference between String
and StringBuilder
(StringBuilder
being mutable) but is there a large performance difference
StringBuilder
is better for building up a string from many non-constant values.
If you're building up a string from a lot of constant values, such as multiple lines of values in an HTML or XML document or other chunks of text, you can get away with just appending to the same string, because almost all compilers do "constant folding", a process of reducing the parse tree when you have a bunch of constant manipulation (it's also used when you write something like int minutesPerYear = 24 * 365 * 60
). And for simple cases with non-constant values appended to each other, the .NET compiler will reduce your code to something similar to what StringBuilder
does.
But when your append can't be reduced to something simpler by the compiler, you'll want a StringBuilder
. As fizch points out, that's more likely to happen inside of a loop.
String and StringBuilder are actually both immutable, the StringBuilder has built in buffers which allow its size to be managed more efficiently. When the StringBuilder needs to resize is when it is re-allocated on the heap. By default it is sized to 16 characters, you can set this in the constructor.
eg.
StringBuilder sb = new StringBuilder(50);
This benchmark shows that regular concatenation is faster when combining 3 or fewer strings.
http://www.chinhdo.com/20070224/stringbuilder-is-not-always-faster/
StringBuilder can make a very significant improvement in memory usage, especially in your case of adding 500 strings together.
Consider the following example:
string buffer = "The numbers are: ";
for( int i = 0; i < 5; i++)
{
buffer += i.ToString();
}
return buffer;
What happens in memory? The following strings are created:
1 - "The numbers are: "
2 - "0"
3 - "The numbers are: 0"
4 - "1"
5 - "The numbers are: 01"
6 - "2"
7 - "The numbers are: 012"
8 - "3"
9 - "The numbers are: 0123"
10 - "4"
11 - "The numbers are: 01234"
12 - "5"
13 - "The numbers are: 012345"
By adding those five numbers to the end of the string we created 13 string objects! And 12 of them were useless! Wow!
StringBuilder fixes this problem. It is not a "mutable string" as we often hear (all strings in .NET are immutable). It works by keeping an internal buffer, an array of char. Calling Append() or AppendLine() adds the string to the empty space at the end of the char array; if the array is too small, it creates a new, larger array, and copies the buffer there. So in the example above, StringBuilder might only need a single array to contain all 5 additions to the string-- depending on the size of its buffer. You can tell StringBuilder how big its buffer should be in the constructor.
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.
If you're doing a lot of string concatenation, use a StringBuilder. When you concatenate with a String, you create a new String each time, using up more memory.
Alex
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.
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.
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: