Tuesday, January 06, 2015

Difference between String and Stringbuilder in C#, Asp.net

 I will explain what is difference between string and stringbuilder in c# using asp.net.

String is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create new instance in memory to hold the new value.

string str = "AoA";
// create a new string instance instead of changing the old one
str += "Good";
str += " morning";

Good morning

String builder:
String builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.


StringBuilder sb = new StringBuilder("");
sb.Append("Good morning");
string str = sb.ToString();

AoA Good morning

It’s an immutable
It’s mutable
Performance wise string is slow because every time it will create new instance
Performance wise stringbuilder is high because it will use same instance of object to perform any action
In string we don’t have append keyword
In StringBuilder we can use append keyword
String belongs to System namespace
Stringbuilder belongs to System.Text namespace

Default String builder capacity
String builder default string builder capacity is only 16 characters! so if you keep on appending more than 16 characters, the original string builder object will be discarded and a new one with double the capacity will be generated internally.

If you know before hand at least approximate number of characters you will be storing in the string builder, it would be a performance booster to define the string builder with desired capacity.

e.g., StringBuilder sb = new StringBuilder(7000);

This will create the string builder sb with default capacity 7000 characters, if you append even 1 character more than 7000, a new object with capacity of 14000 characters will be created automatically which could become a performance problem if you are using string builder liberally!!

No comments:

Post a Comment