StringBuilder for performance in Kotlin - Time & Space Complexity
When building strings repeatedly, the way we add pieces affects how long it takes.
We want to see how using StringBuilder changes the work as the string grows.
Analyze the time complexity of the following code snippet.
fun buildString(n: Int): String {
val sb = StringBuilder()
for (i in 1..n) {
sb.append(i)
}
return sb.toString()
}
This code adds numbers from 1 to n into a StringBuilder, then returns the combined string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Appending a number to the StringBuilder inside a loop.
- How many times: Exactly n times, once for each number from 1 to n.
Each time we add a number, the work grows a little, but StringBuilder helps keep it steady.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 appends |
| 100 | About 100 appends |
| 1000 | About 1000 appends |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to build the string grows in a straight line as the input size grows.
[X] Wrong: "Using StringBuilder is slow because it copies the whole string every time we add something."
[OK] Correct: StringBuilder keeps extra space and adds new parts without copying everything each time, so it stays fast.
Understanding how StringBuilder helps with performance shows you know how to handle growing data efficiently, a useful skill in many coding tasks.
"What if we used regular string concatenation (+) inside the loop instead of StringBuilder? How would the time complexity change?"