Skip to content

Commit ce221f0

Browse files
committed
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]>
1 parent c5ad32f commit ce221f0

File tree

1 file changed

+23
-112
lines changed

1 file changed

+23
-112
lines changed
Lines changed: 23 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
1-
public class StringImmutable
2-
{
3-
public static void main(String[] args)
4-
{
5-
// Example usage of both methods:
1+
public class StringImmutable {
2+
public static void main(String[] args) {
63
StringImmutable si = new StringImmutable();
74

85
String result1 = si.appendNtimesUsingStringConcat('A', 5);
@@ -13,128 +10,42 @@ public static void main(String[] args)
1310
System.out.println(result2); // Output: BBB
1411
}
1512

16-
// O(n^2)
17-
public String appendNtimesUsingStringConcat(char c, int n)
18-
{
13+
// Inefficient: O(n^2) complexity.
14+
// Har iteration me new String banega (String immutable hoti hai).
15+
// str += c ka matlab hai ek naya object banta hai aur purane characters copy hote hain.
16+
public String appendNtimesUsingStringConcat(char c, int n) {
1917
String str = "";
20-
for (int i = 0; i < n; i++)
21-
{
18+
19+
for (int i = 0; i < n; i++) {
2220
str += c; // O(s) where s = length(str)
2321
}
2422
return str; // Return the result as a String
2523
}
2624

27-
// O(n)
25+
// Efficient: O(n) complexity.
26+
// StringBuilder mutable hota hai → har append O(1) time me hota hai.
2827
public String appendNtimesUsingStringBuilder(char c, int n) {
2928
StringBuilder sb = new StringBuilder();
29+
3030
for (int i = 0; i < n; i++) {
3131
sb.append(c); // O(1)
3232
}
33-
return sb.toString(); // Return the result as a String
33+
return sb.toString();
3434
}
3535
}
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.
61-
62-
### 4. **Using `appendNtimesUsingStringConcat`:**
63-
64-
```java
65-
String result1 = si.appendNtimesUsingStringConcat('A', 5);
66-
System.out.println(result1); // Output: AAAAA
67-
```
68-
Here, we call the method `appendNtimesUsingStringConcat` with two arguments:
69-
- `'A'` (the character we want to append).
70-
- `5` (the number of times we want to append the character to the string).
71-
72-
The method returns a string of `5` repeated `'A'` characters, and we print it.
73-
74-
### 5. **Using `appendNtimesUsingStringBuilder`:**
7536

76-
```java
77-
String result2 = si.appendNtimesUsingStringBuilder('B', 3);
78-
System.out.println(result2); // Output: BBB
79-
```
80-
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.
85-
86-
### 6. **Method 1: `appendNtimesUsingStringConcat`:**
87-
88-
```java
89-
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.
103-
104-
### 7. **Method 2: `appendNtimesUsingStringBuilder`:**
105-
106-
```java
107-
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.
13341
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.
13545
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.
13747
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.
14051
*/

0 commit comments

Comments
 (0)