String vs StringBuilder in Java - Performance Comparison
We want to see how fast string operations run when using String and StringBuilder.
How does the time to build or change a string grow as the string gets longer?
Analyze the time complexity of the following code snippet.
String result = "";
for (int i = 0; i < n; i++) {
result += i;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(i);
}
String finalResult = sb.toString();
This code builds a string by adding numbers from 0 to n-1 using two ways: String concatenation and StringBuilder.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding a number to the string inside a loop.
- How many times: The loop runs n times, repeating the add operation each time.
When using String concatenation, each add creates a new string copying old content, so work grows quickly.
| Input Size (n) | Approx. Operations (String) | Approx. Operations (StringBuilder) |
|---|---|---|
| 10 | About 55 copies | About 10 appends |
| 100 | About 5,050 copies | About 100 appends |
| 1000 | About 500,500 copies | About 1000 appends |
Pattern observation: String concatenation work grows much faster than StringBuilder as n grows.
Time Complexity: O(n^2) for String concatenation, O(n) for StringBuilder
Using String concatenation takes much more time as the string grows, but StringBuilder stays fast and grows evenly.
[X] Wrong: "Using + to add strings in a loop is always fast enough for any size."
[OK] Correct: Each + creates a new string copying all old content, so time grows very fast and slows down big loops.
Knowing when to use StringBuilder shows you understand how code speed changes with input size, a key skill in programming.
"What if we used StringBuffer instead of StringBuilder? How would the time complexity change?"
