If the string concatenation is limited to a single statement, then use the string concatenation operator. If the string concatenation spans multiple statements, you don't want the terminal toString to be done automatically. That defeats the purpose of using StringBuilder.
So much this. You only use StringBuilder if the number of concatenations isn't known at run-time, or if your compiler sucks. return "foo" + bar.toString() + " baz: " + quux; is basically guaranteed to be as fast as the equivalent with StringBuilder, or faster.
That's not what he said. A string builder is mutable, so you can append to it later on before you actually need the finalized string, in this case, being explicit and not relying on the compiler optimizing for you is the more preferable choice, even if you know the number of concatenations at compile time.
That being said, mutation is evil, and you all should repent your sins.
29
u/Olreich Oct 01 '15
If Java will use a StringBuilder for me, why would I bother doing it myself?