Difference between String and StringBuilder ?

 Updated on October 09, 2014     VIKRAM     2024

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.

Example:

string str = "hi";
str += "hello"; // New string instance will be created, instead of changing the old one
str += "hw r u"; // Again new string instance will be created, instead of changing the old one

StringBuilder:

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.

Example:

StringBuilder sb = new StringBuilder("");
sb.Append("hi");
sb.Append("hello");
string str = sb.ToString();

Differences:

String StringBuilder
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

If you enjoyed this post, please like (or) share this article.


Comments