Concatenate over Format
String.format()
is generally more readable than it's counterpart of String concatenation:
void formatValues(String firstName, String lastName, int age) {
return String.format("Welcome %s %s, you are %d years old!", firstName, lastName, age);
}
void concatenateValues() {
return "Welcome " + firstName + " " + lastName + ", you are " + age + " years old!";
}
The performance however of String.format()
is generally far worse compared to concatenation, and for a smaller number
of operations (less than 10k) the difference in performance between StringBuilder
and the +
operation is negligible.
Benchmark
Definition
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 200, time = 1, timeUnit = TimeUnit.MILLISECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class StringConcatenationBenchmark {
private String uuid1;
private String uuid2;
private String uuid3;
@Setup
public void setup() {
uuid1 = UUID.randomUUID().toString();
uuid2 = UUID.randomUUID().toString();
uuid3 = UUID.randomUUID().toString();
}
@Benchmark
public String concatenate_string() {
return uuid1 + " - " + uuid2 + " - " + uuid3;
}
@Benchmark
public String format_string() {
return String.format("%s - %s - %s", uuid1, uuid2, uuid3);
}
@Benchmark
public String string_builder() {
return new StringBuilder(uuid1).append(" - ").append(uuid2).append(" - ").append(uuid3).toString();
}
}
Results
As can be seen from the results below, there's a marginal performance increase of 2.4% using StringBuilder
over
concatenation. However, there's a 667.7% increase in performance using +
compared to String.format()
!
Benchmark | Mode | Count | Score | Error | Units |
---|---|---|---|---|---|
StringConcatenationBenchmark.concatenate_string | avgt | 200 | 121.715 | ± 16.742 | ns/op |
StringConcatenationBenchmark.format_string | avgt | 200 | 946.532 | ± 271.592 | ns/op |
StringConcatenationBenchmark.string_builder | avgt | 200 | 124.590 | ± 41.864 | ns/op |