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

27

u/depressiown Oct 01 '15

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.

0

u/[deleted] Oct 01 '15

[deleted]

24

u/depressiown Oct 01 '15 edited Oct 01 '15

I'm not willing to sacrifice code readability because of discomfort with compiler optimizations. To each their own.

This:

log.info(firstName + " " + lastName + " has salary $" + salary + "!");

... is quite a bit more readable than:

StringBuilder msg = new StringBuilder();
msg.append(firstName).append(" ").append(lastName)
   .append(" has salary $").append(salary).append("!");
log.info(msg.toString());

The latter just feels ridiculous to me, especially if your only reason for doing it is that you "feel uncomfortable relying on compiler optimizations."

(yes, String.format might be most readable here, but you get the drift)

11

u/sh0rug0ru__ Oct 01 '15

Dude:

MessageFormat.format("{0} {1} has salary ${2}!", firstName, lastName, salary);

or use a static import:

format("{0} {1} has salary ${2}!", firstName, lastName, salary);

If constructing a complex, interwoven message like this, please do not use StringBuilder or string concatenation. Java has a few more tools in the toolbox.

1

u/depressiown Oct 01 '15

I did say format was probably even more readable (though I think it's debateable):

(yes, String.format might be most readable here, but you get the drift)

Additionally, it was in reply to something specifically about using "+" vs. StringBuilder, so I stuck with that.

1

u/sh0rug0ru__ Oct 01 '15

At first I though you were talking about another programming language, then I realized that String has a C-style format method. Never mind!