Card 07/ 09
All 9 cards
ComparisonDifficulty: Intermediate1 min
String, StringBuilder and StringBuffer on Three Axes
Three types that all hold text. Two of them can be changed in place, and the difference between those two is a decision somebody made in 1996 and a decision somebody made in 2004.
| Type | Can be changed in place | Safe across threads | Reach for it when |
|---|---|---|---|
String | No | Yes, because nothing can change it | The text is a value you pass around |
StringBuilder | Yes | No | You are assembling text in a loop or a method |
StringBuffer | Yes | Yes, every method is synchronised | Two threads genuinely share one builder |
StringBuilder row = new StringBuilder();
for (String value : values) {
row.append(value).append(",");
}
String result = row.toString();append writes into a character array the builder already owns, growing it in jumps when it runs out. Nothing is copied per pass, so a thousand appends cost about a thousand times one append rather than a thousand squared.
The decision rule. Use String for text you hold and hand around. Use StringBuilder the moment you are assembling text in a loop. Use StringBuffer only when two threads append to the same builder, which is rare enough that meeting it should make you check the design first.