String Builder vs. String Buffer
Since standard Strings are immutable, creating a string inside a loop (like s = s + “a”) is a performance disaster. It creates N new objects for N iterations. To solve this, Java provides StringBuilder and StringBuffer. They are mutable (modifiable) sequences of characters.
| Feature | String | StringBuilder | StringBuffer |
| Modifiable? | No (Immutable) | Yes (Mutable) | Yes (Mutable) |
| Performance | Slow for concatenation | Fastest | Moderate |
| Thread Safe? | Yes | No | Yes (Synchronized) |
| Use Case | Storing constants, IDs | Building strings in loops | Multi-threaded apps |
Code Example: Efficient String Manipulation
JavaPythonCC++
public class StringBuilderDemo {
public static void main(String[] args) {
// Inefficient way (Don't do this in large loops!)
String slow = "";
for(int i=0; i<5; i++) {
slow = slow + i; // Creates 5 new objects
}
// Efficient way (Use StringBuilder)
StringBuilder sb = new StringBuilder();
for(int i=0; i<5; i++) {
sb.append(i); // Modifies the existing object
}
// Convert back to String when done
String fast = sb.toString();
System.out.println(fast); // Output: 01234
// Reverse a String (Easy with StringBuilder)
System.out.println("Reversed: " + sb.reverse().toString()); // Output: 43210
}
}
# Inefficient way (String concatenation in loop)
slow = ""
for i in range(5):
slow = slow + str(i) # Creates new string each time
# Efficient way (Using list builder approach)
sb = []
for i in range(5):
sb.append(str(i)) # Modifies existing list
# Convert back to string
fast = "".join(sb)
print(fast) # Output: 01234
# Reverse a String
print("Reversed:", fast[::-1]) # Output: 43210
#include <stdio.h>
#include <string.h>
int main() {
// Inefficient way
char slow[50] = "";
for(int i = 0; i < 5; i++) {
char temp[2];
sprintf(temp, "%d", i);
strcat(slow, temp); // Repeated concatenation
}
// Efficient way (manual building)
char fast[50];
int index = 0;
for(int i = 0; i < 5; i++) {
fast[index++] = '0' + i;
}
fast[index] = '\0';
printf("%s\n", fast); // Output: 01234
// Reverse String
int len = strlen(fast);
printf("Reversed: ");
for(int i = len - 1; i >= 0; i--) {
printf("%c", fast[i]);
}
printf("\n");
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
// Inefficient way
string slow = "";
for(int i = 0; i < 5; i++) {
slow = slow + to_string(i);
}
// Efficient way (Using string builder style)
string fast = "";
for(int i = 0; i < 5; i++) {
fast.append(to_string(i));
}
cout << fast << endl; // Output: 01234
// Reverse String
string reversed = string(fast.rbegin(), fast.rend());
cout << "Reversed: " << reversed << endl; // Output: 43210
return 0;
}