Skip to content
Advertisement

Most efficient way to concatenate Strings

I was under the impression that StringBuffer is the fastest way to concatenate strings, but I saw this Stack Overflow post saying that concat() is the fastest method. I tried the 2 given examples in Java 1.5, 1.6 and 1.7 but I never got the results they did. My results are almost identical to this

  1. Can somebody explain what I don’t understand here? What is truly the fastest way to concatenate strings in Java?

  2. Is there a different answer when one seeks the fastest way to concatenate two strings and when concatenating multiple strings?

Advertisement

Answer

String.concat is faster than the + operator if you are concatenating two strings… Although this can be fixed at any time and may even have been fixed in java 8 as far as I know.

The thing you missed in the first post you referenced is that the author is concatenating exactly two strings, and the fast methods are the ones where the size of the new character array is calculated in advance as str1.length() + str2.length(), so the underlying character array only needs to be allocated once.

Using StringBuilder() without specifying the final size, which is also how + works internally, will often need to do more allocations and copying of the underlying array.

If you need to concatenate a bunch of strings together, then you should use a StringBuilder. If it’s practical, then precompute the final size so that the underlying array only needs to be allocated once.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement