Difference between System.String and System.Text.StringBuilder in C# (C Sharp)?
Difference between System.String and System.Text.StringBuilder in C# (C Sharp)?
If you know C#, you must know the difference between String and StringBuilder Class. When to use what and why? There is a basic difference of performance and speed in String and StringBuilder class which I will try to highlight here with the help of a simple example.
Suggestion: If you are going for interview on ASP.NET with C#, you must prepare this basic question of difference between String and StringBuilder in C#.
Now, lets starting exploring the difference between String and SringBuilder:
1. Performance of StringBuilder is high
Lets take an example to illustrate this concept. StringBuilder will deliver high performance as compared to String when you are concatenating the strings like following:
String s= "";
s+= "abc ";
s+= "pqr ";
s+= "xyz";
s+= "abc ";
s+= "pqr ";
s+= "xyz";
Same can be done using StringBuilder class
StringBuilder sb = new StringBuilder("");
sb.Append("abc");
sb.Append("pqr ");
sb.Append("xyz");
String s = sb.ToString();
sb.Append("abc");
sb.Append("pqr ");
sb.Append("xyz");
String s = sb.ToString();
Now in both case when I used String and StringBuilder, the end result is same, but performance issues are there with String class. String always create new object of string type in memory when the concatenation happens while when you use string builder class, it updates string at one place in memory and does not create new space in memory. So in this way StringBuilder consumes less memory and delivers high speed. So we can say that StringBuilder is more efficient for operations that manipulate strings.
2. StringBuilder is a Mutable Class while String is Immutable
This point is the extension of the point 1. Let me explain the meaning of mutable and immutable class.
StringBuilder is mutable means that you can insert, append, replace etc. without creating a new StringBuilder each time.
String is immutable means that each time you perform an operation like insert, append, replace etc. that "changes" it, you are creating a new string to replace the old one. You create a string you can never change it, rather it will create a new string to store the new value, this can be inefficient if you need to change the value of a string variable a lot.
Like in the above example, we are concating many values to the String s which in turn is creating new instances of String s and the destroying it and we are ending up with only the final String which looks like s= "abc pqr xyz ". But StringBuilder will not create multiple instances of StringBuilder sb while concatenating.
3. String class belongs to the namespace System while StringBuilder class belongs to the namespace System.Text.