Java string concatenate examples with times

Three ways to concatenate in Java:

  • by using operator +=
  • by new StringBuilder(str4).append(str1)
  • by method concant()

Concatenate Java string by +=

The easiest to remember and use seems to be +=. But also it's the slowest one:

String str1 = "I'm a ";
String str2 = " simple ";
String str3 = " string ";

String str4 = "";
str4 += str1 += str2 += str3;
System.out.println(str4);

result:

I'm a simple string

Concatenate Java string by StringBuilder and append

Another way is by using string builder and append. It's a bit faster then +=. You can check chapter concatenation timings for the test and the results:

String str1 = "I'm a ";
String str2 = " simple ";
String str3 = " string ";

String str = new StringBuilder(str1).append(str2).append(str3).toString();
System.out.println(str);

result:

I'm a simple string

Concatenate Java string by concant

The fastest way to concatenate strings in Java according to my tests seems to be concat. For 50 000 concatenations is three times faster than += and two times faster than StringBuilder:

String str1 = "I'm a ";
String str2 = " simple ";
String str3 = " string ";

String str = "";
str = str1.concat(str2).concat(str3);
System.out.println(str);

result:

I'm a simple string

Timings for the three options

Timings are measured simply by calculating the start and the end time of executions. Next time I'll do the same test by using microbenchmark and JMH library. You can check more about java and benchmarking here:

Java benchmarks examples

This is a sample test code:

//
// Start , action and end
//
long start = System.nanoTime();
//
// Test code start
//
String str1 = "I'm a ";
String str2 = " simple ";
String str3 = " string ";
String str4 = str1;
for (int i=0; i < 50000; i++){
    str4 += str1;
}
System.out.println(str4);
//
// Test code end
//
long elapsedTime = System.nanoTime() - start;
double secondDecimalPrecision = (double)elapsedTime / 1000000000.0;

The results for all of them:

  1. 50 000 times - +=
  • Seconds: 8.885309
  1. 50 000 times - new StringBuilder(str4).append(str1)
  • Seconds: 5.605033
  1. 50 000 times - str1.concat(str2)
  • Seconds: 2.994370