StringBuilder and string are both used to string values, but both have many differences on the bases of instance creation and also in performance.
String
A string is an immutable object. Immutable is when we create string objects in code so we cannot modify or change that object in any operations like insert new value, replace or append any value with the existing value in a string object. When we have to do some operations to change string simply it will dispose of the old value of string object and it will create a new instance in memory for hold the new value in a string object, for example:
- It’s an immutable object that holds a string value.
- Performance-wise, string is slow because it creates a new instance to override or change the previous value.
- String belongs to the System namespace.
StringBuilder
System.Text.Stringbuilder is a mutable object which also holds the string value, mutable means once we create a System.Text.Stringbuilder object. We can use this object for any operation like insert value in an existing string with insert functions also replace or append without creating a new instance of System.Text.Stringbuilder for every time so it’s using the previous object. That way, it works fast compared to the System.String. Let’s see an example to understand System.Text.Stringbuilder.
Note
- StringBuilder is a mutable object.
- Performance-wise StringBuilder is very fast because it will use the same instance of StringBuilder object to perform any operation like inserting a value in the existing string.
- StringBuilder belongs to System.Text.Stringbuilder namespace.