Commit 54b4ab5
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
1 file changed
+38
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | 1 | | |
3 | 2 | | |
4 | 3 | | |
5 | 4 | | |
6 | 5 | | |
7 | 6 | | |
| 7 | + | |
8 | 8 | | |
9 | 9 | | |
10 | 10 | | |
| |||
15 | 15 | | |
16 | 16 | | |
17 | 17 | | |
| 18 | + | |
18 | 19 | | |
19 | 20 | | |
20 | 21 | | |
21 | | - | |
22 | 22 | | |
23 | 23 | | |
24 | 24 | | |
25 | 25 | | |
26 | 26 | | |
27 | 27 | | |
28 | | - | |
29 | 28 | | |
| 29 | + | |
30 | 30 | | |
31 | 31 | | |
32 | 32 | | |
33 | | - | |
34 | 33 | | |
35 | 34 | | |
36 | 35 | | |
37 | | - | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
| 65 | + | |
| 66 | + | |
| 67 | + | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
0 commit comments