I wrote a quick caliper benchmark to compare String.format()
vs. StringBuilder
, StringBuffer
, normal String
+
operator, String.replace()
and String.concat()
methods:
public class StringFormatBenchmark extends SimpleBenchmark {
public void timeStringFormat(int reps) {
while (--reps >= 0) {
String s = String.format("test %d", reps);
}
}
public void timeStringBuilder(int reps) {
while (--reps >= 0) {
String s = new StringBuilder("test ").append(reps).toString();
}
}
public void timeStringBuffer(int reps) {
while (--reps >= 0) {
String s = new StringBuffer("test ").append(reps).toString();
}
}
public void timeStringPlusOperator(int reps) {
while (--reps >= 0) {
String s = "test " + reps;
}
}
public void timeReplace(int reps) {
while (--reps >= 0) {
String s = "test {}".replace("{}", String.valueOf(reps));
}
}
public void timeStringConcat(int reps) {
while (--reps >= 0) {
String s = "test ".concat(String.valueOf(reps));
}
}
public static void main(String[] args) {
new Runner().run(StringFormatBenchmark.class.getName());
}
}
The results follow (Java 1.6.0_26-b03, Ubuntu, 32 bits):
Clearly String.format()
is much slower (by an order of magnitude). Also StringBuffer
is considerably slower than StringBuilder
(as we were taught). Finally StringBuilder
and String
+
operator are almost identical since they compile to very similar bytecode. String.concat()
is a bit slower.
Also don't use String.replace()
if simple concatenation is sufficient.