String and StringBuilder class
are used to handle the strings but there are many differences between these two,
regarding their use and namespace to which they belong.
In this article I will
explain the difference between String and StringBuilder class in ASP.NET with
C# and When to use String and when to use StringBuilder and why?
1.
Performance :
Performance
of string builder is high as compared to string.
Consider the
following concatenation example:
String str=
"";
str += "Say ";
str += " Hello ";
str += "To World";
str += "Say ";
str += " Hello ";
str += "To World";
Output string will
be Say Hello To World.
Let's do the same
concatenation operation using StringBuilder class
StringBuilder sb =
new StringBuilder("");
sb.Append("Say ");
sb.Append("Hello ");
sb.Append("To World ");
String str = sb.ToString();
sb.Append("Say ");
sb.Append("Hello ");
sb.Append("To World ");
String str = sb.ToString();
Output string will
be Say hello To World.
Output is same in both the cases. Then how can we measure the
performance difference?
Whenever we concatenate new string to the old
string then String class always create new object of string type in memory
whereas in case of string builder class, does not create new space in
memory and update the same string.
So it is clear
string builder consume less space than string. So it is recommended to use
string builder to manipulate string.
2) String
Concatenation can be done using '+' operator or using the String.Concat method whereas in case of StringBuilder we use Append() method to
concatenate.
3) String is Immutable (Non Modifiable) whereas StringBuilder is a
Mutable Class
String
is immutable: Every time we
concatenate new string to old, string class create new object of string type. So
it cannot be modify.
StringBuilder is mutable. It means in case
of string builder class, does not create new space in
memory and update the same string.
4) String
class comes under namespace System while StringBuilder class belongs to the
namespaceSystem.Text.
5) When string
concatenation takes place, additional memory will be allocated whereas in case of StringBuffer additional memory will be allocated only when the string
buffer capacity exceeds.
When
to use String or StringBuilder Class?
If string
manipulation is small then we should use string class, extra memory is
affordable in that case. But for large string manipulations it is recommended
to use StringBuilder class, because it uses less space than string.
0 comments:
Post a Comment