Skip to content

Instantly share code, notes, and snippets.

@darichey
Created January 27, 2019 23:19
Show Gist options
  • Save darichey/9885fbb481f8eb6452a4b91116128190 to your computer and use it in GitHub Desktop.
Save darichey/9885fbb481f8eb6452a4b91116128190 to your computer and use it in GitHub Desktop.
String concat performance

String concatenation performance is a funny thing. Java 6-8, all string concat will be done with a StringBuilder. However, what we're actually concerned with is string concatenation in a loop. This is where the compiler does not make an optimization. A new StringBuilder will be allocated and used to concatenate to the String for every iteration of the loop. Because of this, for Java 8 and below, the definite advice is to change to a StringBuilder manually when doing concatenation in a loop.

Here's where things get interesting though. As of Java 9, javac no longer straight up converts to StringBuilder for all string concatenations. Instead, it uses invokedynamic. This means that at runtime many different strategies for concatenation can be chosen for code generation (one of which is still StringBuilder, for example). Because of this, the advice isn't so straight forward. As of today, manually converting to StringBuilder (as was done in the past) will likely yield better performance. However, the use of invokedynamic allows for new, better string concatenation strategies to be added in the future. In such a case that a strategy which is better than a single StringBuilder is better, if you use "+=" you will automatically benefit from this change. If you were manually using StringBuilder, you'll have to update your code to benefit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment