Why appending to a string in Java can become O(n²).
š“ Problem: Strings are immutable in Java
When you do:
Each += operation:
-
Creates a new String
-
Copies all characters from the old string
-
Appends the new character
So, internally it works like this:
If you do this in a loop n times:
The cost of each iteration is increasing:
-
First iteration: O(1)
-
Second: O(2)
-
Third: O(3)
-
...
-
n-th iteration: O(n)
➡️ Total time = 1 + 2 + 3 + ... + n = O(n²)
✅ Solution: Use StringBuilder
-
StringBuildermaintains an internal buffer. -
It grows efficiently without copying the entire string each time.
-
Each
append()is O(1) amortized, so total time = O(n).
š Summary
| Method | Time Complexity | Reason |
|---|---|---|
str1 + str2 once | O(n + m) | Copies both strings once. |
+= in a loop (String) | O(n²) | Creates a new string each time, copying the full old one. |
StringBuilder.append() | O(n) | Uses resizable buffer, appends in constant time amortized. |
No comments:
Post a Comment