Careeroza
StringBuffer and Comparison
String vs StringBuilder vs StringBuffer
String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Mutable | no | yes | yes |
| Thread-safe | yes (immutable) | no | yes (synchronized methods) |
| Speed | slow for repeated changes | fastest | slower than StringBuilder |
| Since | Java 1.0 | Java 5 | Java 1.0 |
| Use for | fixed text, keys, constants | building text in one thread (almost always) | legacy code; shared buffer across threads |
Same API
Example
StringBuffer has the same methods as StringBuilder; only the synchronisation differs.
public class Main {
public static void main(String[] args) {
StringBuffer log = new StringBuffer();
log.append("[INFO] ").append("Server started");
log.append(" on port ").append(8080);
System.out.println(log);
System.out.println("capacity >= length: " + (log.capacity() >= log.length()));
}
}Output
[INFO] Server started on port 8080 capacity >= length: true
Measuring the Difference
Example
Concatenating with + in a loop copies the whole string each time. The exact timings vary, so this program prints only which approach was faster.
public class Main {
public static void main(String[] args) {
int n = 20000;
long t1 = System.nanoTime();
String s = "";
for (int i = 0; i < n; i++) {
s += "x";
}
long plusTime = System.nanoTime() - t1;
long t2 = System.nanoTime();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append("x");
}
long builderTime = System.nanoTime() - t2;
System.out.println("Both lengths equal: " + (s.length() == sb.length()));
System.out.println("StringBuilder faster: " + (builderTime < plusTime));
}
}Output
Both lengths equal: true StringBuilder faster: true
Note: A single expression like "Hi " + name + "!" is fine; the compiler optimises it. The problem is += inside loops.