StringBuilder and why it exists in C Sharp (C#) - Time & Space Complexity
When working with text in C#, how fast your program runs can change a lot depending on how you build strings.
We want to see why StringBuilder helps and how its speed changes as text grows.
Analyze the time complexity of the following code snippet.
var sb = new System.Text.StringBuilder();
for (int i = 0; i < n; i++)
{
sb.Append(i.ToString());
}
string result = sb.ToString();
This code builds a long string by adding numbers one by one using StringBuilder.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs n times, each time appending text to StringBuilder.
- How many times: Exactly n times, once per number added.
As n grows, the number of append actions grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 appends |
| 100 | About 100 appends |
| 1000 | About 1000 appends |
Pattern observation: The work grows steadily and directly with the number of items added.
Time Complexity: O(n * m)
This means the time to build the string grows linearly with the number of items added and the average length of each item.
[X] Wrong: "Using + to add strings is just as fast as StringBuilder."
[OK] Correct: Adding strings with + creates new strings each time, making work grow much faster than with StringBuilder.
Understanding how StringBuilder helps with many text additions shows you know how to write faster, smarter code when working with strings.
What if we replaced StringBuilder with simple string concatenation inside the loop? How would the time complexity change?