I've been through different topics about String concatenation performance. Almost answer recommend using StringBuilder
or StringBuffer
to reduce overhead cost (or +
operator if concatenation statement outside the loop). It's pretty clear, but I still wonder why Java has String format()
and concat()
method although it's ineffective. Performance test here: link. Someone mentioned String format()
may be useful for Localization
purpose (I don't understand much, howsoever I already have a keyword to search later), but what's the purpose of the remaining one? Does it only useful for compatibility backward?
Asked
Active
Viewed 235 times
-1

logbasex
- 1,688
- 1
- 16
- 22
-
3Format isn't ineffective... Please quote your sources – OneCricketeer Mar 09 '20 at 15:18
-
@cricket_007: [link](https://stackoverflow.com/questions/925423/is-it-better-practice-to-use-string-format-over-string-concatenation-in-java) – logbasex Mar 09 '20 at 15:19
-
2@logbasex That link doesn't say anything is ineffective. – khelwood Mar 09 '20 at 15:20
-
[The newer research](http://www.pellegrino.link/2015/08/22/string-concatenation-with-java-8.html): @khelwood – logbasex Mar 09 '20 at 15:22
-
@logbasex Nor does that one. – khelwood Mar 09 '20 at 15:24
-
2Does this answer your question? [String concatenation: concat() vs "+" operator](https://stackoverflow.com/questions/47605/string-concatenation-concat-vs-operator) – Bentaye Mar 09 '20 at 15:24
-
@Bentaye: It doesn't. I don't know why we need String `concat()` method while the better one is available. – logbasex Mar 09 '20 at 15:28
-
1@logbasex it states "The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance." and `+` uses StringBuilder – Bentaye Mar 09 '20 at 15:30
-
1@Bentaye The implementation changed in Java 9 (see [JEP 280: Indify String Concatenation](https://openjdk.java.net/jeps/280)) and now appears to use [`java.lang.invoke.StringConcatFactory`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/invoke/StringConcatFactory.html). – Slaw Mar 09 '20 at 15:42
-
@Slaw fair enough – Bentaye Mar 09 '20 at 15:42
1 Answers
2
String#concat
and +
exist to provide a minimalistic set of operations on the type String.
They are not efficient if used multiple times.
But they have their own right as type operations "xxx" + "yyy"
you do not want to specify using a StringBuilder. (Furthermore there it is a compile time concatenation.)
StringBuffer
is a mistake IMHO. It is slower that the newer StringBuilder
as it is synchronized, but one would rarely add something rom two threads (unordered).
String::concat
may be a method reference useful for stream reduction or such.

Joop Eggen
- 107,315
- 7
- 83
- 138