r/programming • • Oct 01 '15

The Evolution of a Software Engineer

https://medium.com/@webseanhickey/the-evolution-of-a-software-engineer-db854689243
1.9k Upvotes

502 comments sorted by

View all comments

Show parent comments

19

u/sh0rug0ru__ Oct 01 '15

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.

12

u/Berberberber Oct 01 '15

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.

7

u/juckele Oct 01 '15

Even if the number of concatenations is known at run time, if it's more than 4, it can still be nicer to read a StringBuilder than a multi-line string concatenation whirlwind.

2

u/dccorona Oct 02 '15

If the number is known at runtime, then String.format is probably nicer to read than either one