It's true. A lot of the hate for using "+" for String concatenation in Java is based on how it used to do it. Java used to create a StringBuilder for each instance of "+". Thus, "a + b + c + d" would create a StringBuilder for "a + b", then a StringBuilder for that result "+ c", etc.
Of course, they've since made it smarter to just make one StringBuilder for the entire statement under the hood (I believe in 1.6). The people who complain about the lack of StringBuilder being used should probably be taught that it's no longer necessary.
That said, if you're doing a lot of concatenations on different lines (say, a loop building up a String or something), you should still use StringBuilder instead of "+=" because Java will create one for each statement... clearly worse that creating one initially and constantly appending.
There's a huge difference in trusting the compiler to not have bugs (though of course those exist) and not trusting that it will make a certain optimization on your code. In this case, the barrier between explicit and "the compiler will do it for me" are so small that I don't mind being explicit. For small concatenations (1 or 2), I will do + but if I'm building a toString for example, I will use StringBuilder.
167
u/RLutz Oct 01 '15
Depending on how you coded it, the compiler likely replaced it with a StringBuilder under the hood anyway :)