Skip to main content

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()!

BenchmarkModeCountScoreErrorUnits
StringConcatenationBenchmark.concatenate_stringavgt200121.715± 16.742ns/op
StringConcatenationBenchmark.format_stringavgt200946.532± 271.592ns/op
StringConcatenationBenchmark.string_builderavgt200124.590± 41.864ns/op