Difference between string and StringBuilder in C#
By FoxLearn 2/7/2025 3:03:24 AM 57
A key difference is that string
is immutable. This means once a string is created, it cannot be changed.
For instance, when you modify a string, a new object is created in memory instead of altering the original one. If you have a string "Hello" and change it to "Hello, World!", it creates a new string object rather than modifying the original "Hello" string.
For example:
string message = "Hello"; message += ", World!"; // creates a new string object
In contrast, StringBuilder
is mutable, meaning you can modify its value without generating a new object each time. When you append, insert, or remove characters from a StringBuilder
, it modifies the existing object, which leads to better performance, especially when performing many operations on the string.
For example:
StringBuilder sb = new StringBuilder("Hello"); sb.Append(", World!"); // appends to the same object
The performance difference becomes especially noticeable when you modify the text repeatedly. If you are performing many operations (like concatenation or insertions) on a string, it is more efficient to use StringBuilder
.
If you are modifying a string more than five times, you should prefer StringBuilder
to avoid unnecessary object creation and improve efficiency.