3

According to https://dzone.com/articles/jdk-9jep-280-string-concatenations-will-never-be-t, I have the following question:

Should I always use + instead of StringBuilder when building/concatenating strings? As I understood, + uses invokedynamic so it is always faster (and more memory friendly) then StringBuilder. Is this right?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
nimo23
  • 5,170
  • 10
  • 46
  • 75
  • 9
    Unless you're concatenating with a loop or something similar, use `+`. – Slaw May 20 '20 at 17:09
  • Are there any other considerations to take into account when replacing all the `StringBuilders` with `+`? – nimo23 May 20 '20 at 17:11
  • 2
    As Slaw mentioned, the actual use-case of `StringBuilder` is not a simple single concat. It is for when you concat multiple times over time, maybe with a loop. And then it is still the better choice. Stuff like `foo + bar + baz` is not an issue. – Zabuzard May 20 '20 at 17:14
  • What about [`String.join()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-) ? – Abra May 20 '20 at 17:16
  • The problem with `+` comes once you do `for (...) { foo += bar; }`. Optimizations can sometimes be smart enough to convert that pattern as well, but still often fail. Especially if things get more complicated. Use a `StringBuilder` for concats over time or during loops. – Zabuzard May 20 '20 at 17:18

0 Answers0