What's the fastest way to concatenate two Strings in Java?

According to the Java specification (and since the very first version of Java), in the section "String Concatenation Operator +" it is said that :
To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression
So basically, using the + operator or StringBuilder.append for variables is basically the same.

  • You can see that concat is faster than StringBuilder only when concatenating only 2 Strings
  • See that when adding more and more Strings, the StringBuilder resulting time is increasing more slowly that using the concat
  • Note that the difference will be more significant when the strings are very long

 Output :




 Source code is available at:

StringConcatenationPerformance.java

Comments

Popular posts from this blog

String