Difference between string and StringBuilder

 

Both string and StringBuilder are used to store the string data type data and manipulating the string data. But string is the data type and whereas StringBuilder is the class.

In case of string we have to user equal(=) operator to assign the string data and to append any data we have to use plus(+) operator as shown below. 

string str = "This is string"; 

str = str + " and it is data type";

 

StringBuilder is the class, to store or modify the data we have to use Append method as shown below. 

 

StringBuilder obj = new StringBuilder(); 

obj.Append("This is StringBuilder"); 

obj.Append("and it is the class");

 

 

Whenever we are changing the data using string data type, the address of variable will changed. That means for each data change the variable removed from memory and new address allocated for variable. So string variables called as immutable.

In case of StringBuilder, each time we do data modification the new data is appended to existing data, so address of object won’t change. StringBuilder is called mutable objects.

To decide whether we have to use  string or StringBuilder, its depending on the usage. If we do data modifications are less, use string variables because this is not object. But in case if we have more data modifications, better to use StringBuilder because it won’t change address of the object for each data modifications.