What is the difference between string and StringBuilder? When would you use each?
5 minbeginner.NETstringperformance
Quick Answer
String is immutable - any modification creates a new object. StringBuilder is mutable and efficient for multiple modifications. Use String for few concatenations or constant values. Use StringBuilder for loops, multiple operations, or building large strings to avoid performance issues.
Detailed Answer
String:
- Immutable - once created, cannot be changed
- Any modification creates a new string object in memory
- Thread-safe by nature (due to immutability)
- Use when: Few modifications, constant strings, or passing data between methods
Example of immutability:
string str = "Hello";
str = str + " World"; // Creates a NEW string object, original "Hello" is garbage collected
StringBuilder:
- Mutable - can be modified without creating new objects
- More efficient for multiple string manipulations
- Not thread-safe (use synchronization if needed)
- Use when: Multiple modifications, loops, or building large strings
Performance comparison:
// BAD PRACTICE - Creates 1000 new string objects
string result = "";
for (int i = 0; i < 1000; i++)
{
result += i.ToString(); // Very inefficient!
}
// GOOD PRACTICE - Modifies same StringBuilder object
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
sb.Append(i.ToString()); // Efficient!
}
string result = sb.ToString();
When to use each:
- String: 1-5 concatenations, constant values, simple operations
- StringBuilder: Loops, multiple operations, building complex strings, performance-critical code