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.
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.
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.
- How to validate email in C#?
- How to get the sizeof a datatype in C#?
- Static vs Singleton in C#
- Difference between == and Equals() Method in C#
- Asynchronous programming with async, await, Task in C#
- How to loop through an enum in C#?
- Generate Random Numbers in C#
- Difference between Two Dates in C#
- Convert int to enum in C#
- BigInteger Data Type in C#
- Convert String to Enum in C#
- Convert an Object to JSON in C#
- Convert JSON String to Object in C#
- DateTime Formats in C#
- How to convert date object to string in C#?
- Compare strings in C#
- How to count elements in C# array?
- Difference between String and string in C#.
- How to get a comma separated string from an array in C#?
- Boxing and Unboxing in C#
- How to convert string to int in C#?