String
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
= "hi";
//
create a new string instance instead of changing the old one
str
+= "test";
str += "help";
|
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("hi");
sb.Append("test ");
string str
= sb.ToString();
|
Example:
class Program
{ static void Main(string[] args) { //for example: string str = "hello"; //Creates a new object when we concatenate any other words along with str variable it does not actually modify the str variable, instead it creates a whole new string. str = str + " to all"; Console.WriteLine(str); StringBuilder s = new StringBuilder("Hi"); s.Append(" To All"); Console.WriteLine(s); Console.Read(); } } |
Differences
String
|
String Builder
|
It’s an immutable
|
It’s mutable
|
Performance wise string is slow because every
time it will create new instance
|
Performance wise string builder is high because
it will use same instance of object to perform any action
|
In string we don’t have append keyword
|
In String Builder we can use append keyword
|
String belongs to System namespace
|
String builder belongs to System.
Text namespace
|
No comments:
Post a Comment