You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
perf: demonstrate inefficiency of String concat vs efficiency of StringBuilder for repeated appends
WHAT changed:
- Added two methods in `StringImmutable`:
1. `appendNtimesUsingStringConcat(char c, int n)` → builds a string via `str += c`.
- Time complexity: O(n²), since each iteration creates a new String object and copies characters.
2. `appendNtimesUsingStringBuilder(char c, int n)` → builds a string using `StringBuilder.append()`.
- Time complexity: O(n), since append is an in-place constant-time operation.
WHY this matters:
- Shows how **String immutability** leads to performance issues in loops.
- Demonstrates why **StringBuilder** is preferred for dynamic string construction.
EXAMPLE OUTPUT:
- `appendNtimesUsingStringConcat('A', 5)` → `AAAAA`
- `appendNtimesUsingStringBuilder('B', 3)` → `BBB`
REAL-WORLD APPLICATIONS:
- **Bad practice (String concat in loops)**:
- Generating repeated characters for padding, formatting, or test data.
- Causes unnecessary object creation → memory overhead + slow execution.
- **Best practice (StringBuilder)**:
- Used in building logs, constructing SQL queries, creating reports, or text processing engines.
- Efficient in scenarios with heavy concatenation in loops.
KEY TAKEAWAYS:
1. String is immutable → concatenation creates new objects every time.
2. StringBuilder is mutable → append modifies the same buffer.
3. StringBuffer works similarly but is synchronized (thread-safe, slower).
4. Rule of thumb:
- Use String for small static text.
- Use StringBuilder for frequent modifications in single-threaded contexts.
- Use StringBuffer in multi-threaded contexts.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>
returnsb.toString();// Return the result as a String
33
+
returnsb.toString();
34
34
}
35
35
}
36
-
/*
37
-
Sure! Let's go through the code step by step:
38
-
39
-
### 1. **Class Declaration:**
40
-
41
-
```java
42
-
public class StringImmutable {
43
-
```
44
-
Here, we declare a public class `StringImmutable`. This class will contain the methods we need for string operations. The class name is chosen to reflect that we're dealing with string immutability (as strings in Java are immutable).
45
-
46
-
### 2. **Main Method:**
47
-
48
-
```java
49
-
public static void main(String[] args) {
50
-
```
51
-
This is the entry point of the Java program. It's a standard `main` method that Java looks for when you run the program. The method is `static`, meaning you don't need to create an instance of the class to run it.
52
-
53
-
Inside this method, we will demonstrate how to use the two string manipulation methods (`appendNtimesUsingStringConcat` and `appendNtimesUsingStringBuilder`).
54
-
55
-
### 3. **Creating an Instance of `StringImmutable`:**
56
-
57
-
```java
58
-
StringImmutable si = new StringImmutable();
59
-
```
60
-
Since the methods `appendNtimesUsingStringConcat` and `appendNtimesUsingStringBuilder` are not `static`, we create an instance of `StringImmutable` (`si`) so we can call those methods on this instance.
Similarly, we call `appendNtimesUsingStringBuilder`, passing:
81
-
- `'B'` (the character to append).
82
-
- `3` (the number of times to append it).
83
-
84
-
This method uses a `StringBuilder` (more efficient for repeated string concatenations) and returns a string of `3` repeated `'B'` characters, which is printed.
public String appendNtimesUsingStringConcat(char c, int n) {
90
-
String str = "";
91
-
for (int i = 0; i < n; i++) {
92
-
str += c; // O(s) where s = length(str)
93
-
}
94
-
return str;
95
-
}
96
-
```
97
-
This method demonstrates **string concatenation** using the `+` operator, which is known to be inefficient for large numbers of concatenations (due to the string immutability in Java).
98
-
99
-
- `String str = "";` initializes an empty string.
100
-
- The `for` loop runs `n` times (based on the number you pass).
101
-
- Each iteration appends the character `c` to `str` using `str += c;`. In Java, this causes the string to be copied and a new one to be created every time because strings are **immutable** (cannot be changed). This operation takes longer as the string grows, resulting in an overall time complexity of `O(n^2)` (quadratic), where `n` is the number of characters you're concatenating.
102
-
- Finally, the method returns the concatenated string.
public String appendNtimesUsingStringBuilder(char c, int n) {
108
-
StringBuilder sb = new StringBuilder();
109
-
for (int i = 0; i < n; i++) {
110
-
sb.append(c); // O(1)
111
-
}
112
-
return sb.toString();
113
-
}
114
-
```
115
-
This method demonstrates the more efficient approach using `StringBuilder` for string concatenation.
116
-
117
-
- `StringBuilder sb = new StringBuilder();` creates a `StringBuilder` object. Unlike strings, `StringBuilder` is mutable, meaning it can grow without creating new objects each time.
118
-
- The `for` loop runs `n` times and appends the character `c` to the `StringBuilder` with `sb.append(c);`. This operation is `O(1)` (constant time) because `StringBuilder` efficiently handles string growth internally.
119
-
- After the loop, `sb.toString()` converts the `StringBuilder` object into a regular string and returns it.
120
-
121
-
Using `StringBuilder` results in better performance with a time complexity of `O(n)` (linear time), as it avoids the costly copying of strings during each iteration.
122
-
123
-
### 8. **Why These Methods Matter:**
124
-
125
-
- The first method (`appendNtimesUsingStringConcat`) uses a simple `+=` operator, but it has inefficient time complexity due to the immutability of strings in Java. It works fine for small `n` values, but for large `n`, the performance degrades drastically.
126
-
- The second method (`appendNtimesUsingStringBuilder`) uses `StringBuilder`, which is designed to be more efficient for such operations. It performs better because `StringBuilder` is mutable and avoids the overhead of string concatenation.
127
-
128
-
### Summary:
129
-
- The code demonstrates two ways to build a string by repeating a character multiple times.
130
-
- The first approach uses string concatenation (`+=`), which has poor performance for large inputs.
131
-
- The second approach uses `StringBuilder`, which is optimized for this task and performs much better.
132
-
- We also included a simple example in the `main` method to show how both methods can be used.
37
+
/*
38
+
1. String immutable hoti hai → har concat new object banata hai.
39
+
- Complexity: O(n^2) when repeatedly appending in loop.
40
+
- Example: "A" + "A" + "A"... har step me purani string copy hoti hai.
133
41
134
-
Let me know if you'd like further clarification!
42
+
2. StringBuilder mutable hai → same buffer ke andar character append hote hain.
43
+
- Complexity: O(n).
44
+
- Isliye loops me zyada fast hota hai.
135
45
136
-
String is immutable, meaning you can't change it once created. When you concatenate two strings, it doesn’t simply add one string at the end of another; it creates a new string (ouch). Use a StringBuilder instead (or string.join() on a list in Python), which essentially is a List<Character>.
46
+
3. StringBuffer bhi similar hai but thread-safe (synchronized), thoda slow hota hai.
137
47
138
-
· String += c → linear
139
-
· StringBuilder.append(c) → constant
48
+
4. General rule:
49
+
- Agar string constant chhoti hai → String okay hai.
50
+
- Agar loop ke andar append karna hai (dynamic building) → StringBuilder best hai.
0 commit comments