
Many beginners write code like this:
String s = "";
for (int i = 0; i < 10000; i++) {
s += i;
}
Looks harmless…
But internally:
- thousands of new String objects are created
That’s why Java provides:
- StringBuilder
- StringBuffer
Why Regular String Is Slow
Strings in Java are immutable.
That means:
s += "Java";
does NOT modify the existing string.
Instead:
- a completely new object is created.
1. StringBuilder
StringBuilder is:
- Mutable
- Fast
- Not thread-safe
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" World");
String result = sb.toString();
Common Methods
sb.insert(5, " Java");
sb.delete(5, 10);
sb.reverse();
2. StringBuffer
StringBuffer is similar to StringBuilder.
Difference:
- It is synchronized (thread-safe).
StringBuffer sbuf = new StringBuffer();
sbuf.append("Thread-safe");
Performance Difference
Inefficient
String s = "";
for (int i = 0; i < 10000; i++) {
s += i;
}
Efficient
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
sb.append(i);
}
String result = sb.toString();
The Real Insight
When strings change frequently:
- mutable objects are much more efficient.
That’s why:
- StringBuilder is preferred in most cases
StringBuffer is used when thread safety matters
String = immutable
StringBuilder = mutable + fast
StringBuffer = mutable + thread-safe
For More Learning: https://www.quipoin.com/tutorial/data-structure-with-java/stringbuilder-vs-stringbuffer
Top comments (0)