StringBuilder methods and performance in C Sharp (C#) - Time & Space Complexity
When working with text in C#, using StringBuilder can affect how fast your program runs.
We want to see how the time it takes changes as the text gets longer.
Analyze the time complexity of the following code snippet.
StringBuilder sb = new 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 from 0 up to n-1 one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs n times, each time appending a small string.
- How many times: Exactly n times, once for each number from 0 to n-1.
As n grows, the number of append operations grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 appends |
| 100 | About 100 appends |
| 1000 | About 1000 appends |
Pattern observation: The work grows in a straight line as n increases.
Time Complexity: O(n * m)
This means the time to build the string grows directly with the number of items added and the average length of each appended string.
[X] Wrong: "Using StringBuilder.Append inside a loop is slow because it copies the whole string every time."
[OK] Correct: StringBuilder is designed to avoid copying the entire string on each append, so appending is fast and grows linearly, not quadratically.
Understanding how StringBuilder works helps you write efficient code when dealing with many string changes, a useful skill in many programming tasks.
"What if we replaced StringBuilder with simple string concatenation inside the loop? How would the time complexity change?"