StringBuilder and StringBuffer in Java - Time & Space Complexity
We want to understand how fast StringBuilder and StringBuffer work when building strings.
How does the time to add characters grow as the string gets longer?
Analyze the time complexity of the following code snippet.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append('a');
}
String result = sb.toString();
This code builds a string by adding the letter 'a' n times using StringBuilder.
- Primary operation: The loop runs n times, each time appending one character.
- How many times: Exactly n times, once per loop iteration.
Each append adds one character, so the work grows as the string grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 appends |
| 100 | About 100 appends |
| 1000 | About 1000 appends |
Pattern observation: The time grows roughly in a straight line as n increases.
Time Complexity: O(n)
This means the time to build the string grows directly with the number of characters added.
[X] Wrong: "Appending characters takes the same time no matter how long the string is."
[OK] Correct: Sometimes the internal array needs to grow, which takes extra time, but overall it still grows linearly.
Understanding how string building scales helps you write efficient code and explain your choices clearly in interviews.
"What if we used String concatenation (+) inside the loop instead of StringBuilder? How would the time complexity change?"
