• String objects are immutable while StringBuilder is the mutable string type
  • string is a sequence of Unicode characters or array of characters
  • A string is represented by class System.String while StringBuilder class is present in System.Text namespace.
  • we can use a StringBuilder to create variables to hold any kind of text which is a sequential collection of characters based on our requirements

 

  • The String class is defined in the .NET base class library. Ia String object is a sequential collection of System.Char objects which represents a string. The maximum size of String object in memory is 2GB or about 1 billion characters.
  • String is an immutable object - it means that whenever you modify its content it will allocate a new string and this takes time (and memory). 
  • Using StringBuilder you modify the actual content of the object without allocating a new one. So use StringBuilder when you need to do many modifications on the string

Mutable means the string which can be changed.

When to use which one:

  • If a string is going to remain constant throughout the program, then use String class object because a String object is immutable.
  • If a string can change (example: lots of logic and operations in the construction of the string) then using a StringBuilder is the best option.

 

Is StringBuilder faster than string concatenation C#?

Usually StringBuilder is faster if you have more than about 5 concats. But even then just concatenating the Strings usually has little overhead (unless it runs in a tight loop). As soon as you reach 10 concats using StringBuilder will likely be favorable.