Skip to content

Commit 54b4ab5

Browse files
committed
perf: benchmark String concatenation vs StringBuilder efficiency
WHAT was added: - Implemented `StringIMP` class to compare performance of: 1. `useStringBuilder(int n)` → appends "a" n times using StringBuilder. 2. `useStringConcat(int n)` → appends "a" n times using plain String concatenation (`+=`). - Measured execution time in seconds using `System.nanoTime()`. WHY this matters: - Demonstrates the severe performance penalty of using `String` concatenation in loops. - Highlights the efficiency of `StringBuilder` for repetitive append operations. KEY RESULTS (example run with n = 150000): - Time elapsed using StringBuilder: ~0.02 seconds - Time elapsed using StringConcat : ~7.9 seconds - StringBuilder was ~395 times faster CONCEPTS: - **String immutability**: - `str += "a";` creates a new String object on each iteration. - Each step copies all previous characters → O(n²) complexity. - **StringBuilder mutability**: - Appends characters in place within a growing buffer. - Amortized O(1) per append → O(n) overall. REAL-WORLD APPLICATIONS: - ❌ Avoid using `+=` inside loops for log aggregation, file parsing, or text generation. - ✅ Use `StringBuilder` when assembling large or dynamic strings. - ✅ Use `StringBuffer` if thread-safety is required (multi-threaded string building). RULE OF THUMB: - For small, fixed strings → use `String`. - For heavy concatenation in single-threaded code → use `StringBuilder`. - For multi-threaded code → use `StringBuffer`. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent c4f1173 commit 54b4ab5

File tree

1 file changed

+38
-5
lines changed

1 file changed

+38
-5
lines changed
Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
// "static void main" must be defined in a public class.
21
public class StringIMP {
32
public static void main(String[] args) {
43
int n = 150000;
54

65
double timeStringBuilder = useStringBuilder(n);
76
double timeStringConcat = useStringConcat(n);
7+
88
System.out.println("Time elapsed using StringBuilder: " + timeStringBuilder + " seconds");
99
System.out.println("Time elapsed using StringConcat : " + timeStringConcat + " seconds");
1010

@@ -15,23 +15,56 @@ static double useStringBuilder(int n) {
1515
long start = System.nanoTime();
1616

1717
StringBuilder sb = new StringBuilder();
18+
1819
for (int i = 0; i < n; i++) {
1920
sb.append("a");
2021
}
21-
2222
long end = System.nanoTime();
2323
return (end - start) / (double) 1000000000;
2424
}
2525

2626
static double useStringConcat(int n) {
2727
long start = System.nanoTime();
28-
2928
String str = "";
29+
3030
for (int i = 0; i < n; i++) {
3131
str += "a";
3232
}
33-
3433
long end = System.nanoTime();
3534
return (end - start) / (double) 1000000000;
3635
}
37-
}
36+
}
37+
38+
/*
39+
1. String immutable hoti hai
40+
- Har baar jab tum `str += "a"` likhte ho, ek naya String object ban jata hai.
41+
- Purane content ko copy karke new String create hoti hai.
42+
- Isliye agar tum 1,50,000 times loop me concatenate karte ho →
43+
har step me naye object banenge aur purana copy hoga.
44+
- Ye process O(n^2) complexity tak pahunch jata hai (badiya inefficient).
45+
46+
2. StringBuilder mutable hota hai
47+
- Ek hi underlying char[] buffer me data add hota hai.
48+
- Jab buffer full hota hai tabhi resize hota hai (doubling strategy).
49+
- Har append `O(1)` average time leta hai.
50+
- Isliye loop ka cost approx O(n) hota hai (linear).
51+
- Ye single-threaded me best performance deta hai.
52+
53+
3. StringBuffer bhi mutable hai lekin synchronized
54+
- Methods synchronized hote hain, matlab multiple threads ek hi object pe safe kaam kar sakte hain.
55+
- Synchronization overhead ki wajah se thoda slow hota hai compared to StringBuilder.
56+
- Agar single-threaded program hai to StringBuilder prefer karna chahiye.
57+
58+
4. Benchmark ka practical difference
59+
- Agar `n = 1,50,000`:
60+
- StringBuilder → milliseconds me kaam complete.
61+
- String concat → seconds lag jayenge.
62+
- Agar `n` aur bada kar diya (e.g., 5,00,000 ya 10,00,000):
63+
- String concat bahut zyada slow ho jayega (sometimes OutOfMemoryError bhi aa sakta hai).
64+
- StringBuilder phir bhi manageable time me kaam karega.
65+
66+
5. General rule of thumb
67+
- ✅ Agar tumhe frequent string modification karni hai → StringBuilder use karo.
68+
- ✅ Multi-threaded environment me → StringBuffer use karo.
69+
- ✅ Agar string constant hai aur change nahi karni → normal String use karo.
70+
*/

0 commit comments

Comments
 (0)