Tutorialsteacher

Follow Us

Difference between string and StringBuilder in C#

In C#, both string and StringBuilder are used to represent text. However, there is one key difference between them.

In C#, a string is immutable. It means a string cannot be changed once created. For example, a new string, "Hello World!" will occupy a memory space on the heap. Now, changing the initial string "Hello World!" to "Hello World! from Tutorials Teacher" will create a new string object on the memory heap instead of modifying an original string at the same memory address. This impacts the performance if you modify a string multiple times by replacing, appending, removing, or inserting new strings in the original string.

For example, the following create a new string object when you concatenate a value to it.

Example: String
string greeting = "Hello World!";
greeting += " from Tutorials Teacher."; // creates a new string object

In contrast, StringBuilder is a mutable type. It means that you can modify its value without creating a new object each time.

Example: StringBuilder
StringBuilder sb = new StringBuilder("Hello World!");
sb.Append("from Tutorials Teacher."); //appends to the same object

The StringBuilder performs faster than the string if you modify a string value multiple times. If you modify a string value more than five times then you should consider using the StringBuilder than a string.