String vs StringBuilder in C#
String vs StringBuilder in C#
In C#, both string
and StringBuilder
are used to work with text.
However, they have different performance characteristics and use cases.
Understanding the difference is essential for writing **efficient and optimized code**.
String in C# (Immutable)
A string
in C# is **immutable**, meaning any modification creates a **new string instance**.
This behavior is fine for small modifications but can be inefficient for repeated changes.
Example: String Modification
string str = "Hello";
str += " World"; // Creates a new string instance
Console.WriteLine(str); // Output: Hello World
Here, every time we modify str
, a **new memory allocation** occurs,
making **string operations inefficient in loops or large-scale modifications**.
StringBuilder in C# (Mutable)
The StringBuilder
class is designed for **modifying strings efficiently**.
Unlike string
, it is **mutable**, meaning modifications occur in the same instance,
avoiding unnecessary memory allocations.
Example: Using StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.Append(" World"); // Modifies the existing instance
Console.WriteLine(sb.ToString()); // Output: Hello World
In this example, Append()
modifies the same **StringBuilder** instance
without creating **multiple copies** in memory, leading to better performance.
Performance Benchmark: String vs StringBuilder
Let’s compare **execution time** for repeated string modifications using **string** vs **StringBuilder**:
Benchmark Code:
using System;
using System.Diagnostics;
using System.Text;
class Program
{
static void Main()
{
int iterations = 10000;
Stopwatch stopwatch = new Stopwatch();
// Using String
stopwatch.Start();
string str = "";
for (int i = 0; i < iterations; i++)
{
str += "a"; // Creates a new string each time
}
stopwatch.Stop();
Console.WriteLine("String Time: " + stopwatch.ElapsedMilliseconds + "ms");
// Using StringBuilder
stopwatch.Restart();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < iterations; i++)
{
sb.Append("a"); // Modifies the same instance
}
stopwatch.Stop();
Console.WriteLine("StringBuilder Time: " + stopwatch.ElapsedMilliseconds + "ms");
}
}
In this **benchmark**, StringBuilder is significantly **faster** because it **modifies the same instance**
rather than creating multiple **new instances** like string
.
When to Use String vs StringBuilder?
Scenario | Use string |
Use StringBuilder |
---|---|---|
Fixed or small text | ✅ Recommended (easier to use) | ❌ Not necessary |
Frequent modifications in loops | ❌ Avoid (memory overhead) | ✅ Preferred (efficient modifications) |
Concatenating user input or logs | ❌ Inefficient | ✅ Best choice |
Immutable values needed (security) | ✅ Best choice | ❌ Avoid |
Best Practices
- Use
string
for short, fixed text (e.g., small concatenations, assignments). - Use
StringBuilder
for frequent modifications (e.g., building long text dynamically). - **Avoid
string
in loops** where repeated concatenations happen. - Use **
StringBuilder.Append()
instead of+
concatenation** inside loops.