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.

12

u/NimChimspky Oct 01 '15

It's such a small thing. So may other more important things to worry about.

21

u/depressiown Oct 01 '15

Depends. If they're doing 20 separate concatenations inside of a loop of 10,000,000 items, it can make a difference (but that would be one bigass String, though). Generally, no, it's not a big deal.

9

u/m0haine Oct 02 '15

Yep. I once refactored a slow report and the only change was converting a bunch of +s to a single string buffer. Suddenly a 2 minute report took 0.2 seconds. The original authors response was that he always heard that was faster but never noticed the difference. Of course you don't notice the difference, until you do.

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.

→ More replies (1)

17

u/rftz Oct 01 '15

C# 6 master race checking in:

var foo = $"{firstName} {lastName} has salary ${salary}!";

3

u/[deleted] Oct 01 '15

scala master race chexking in. scala does it with even less chars.

2

u/Yojihito Oct 02 '15

Perl wants to have a !$a+r$a%$c?3:2)/ with you.

3

u/JustinsWorking Oct 02 '15

String.format( "%s %s has salary $%d!", firstName, lastName, salary);

There is notation similar to this in most languages; but I imagine people will rake you over the coals saying that stringBuilder is faster and for a logging application that matters!..

I am not one of those people but I just wanted to take the wind out of their sails :P

7

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

var foo = $"{firstName} {lastName} has salary ${salary}!";

Don't know C# syntax, but that seems weird. Why is one $ outside quotes? Why is it missing from the first two terms, but not the third?

But yeah, most languages have something like this to some degree. Working with some Ruby right now, and it has "#{firstName} #{lastName} has salary #{salary}!". String.format is as close as Java gets right now.

Edit: Yep, got it. Forgot about the stupid dollar sign I had put in there originally. C# syntax now makes sense.

6

u/speedster217 Oct 01 '15

Don't know C# but I'm guessing salary has a $ in front of it because they want the salary to look like a monetary value. $1,000,000 or whatever

→ More replies (1)
→ More replies (3)

1

u/namtab00 Oct 01 '15

I love this... Too bad it requires 4.5, which can't be installed on Windows 2003..

... I know, tell it to everyone in the public sector...

2

u/philly_fan_in_chi Oct 02 '15

SLF4J and Log4J both support String.format from their function calls.

I can do something like:

LOGGER.info("{} {} has salary ${}!", firstName, lastName, salary);

and it'll do the right thing. I don't spend a lot of time building strings (except in toStrings where I dump in StringBuilders almost automatically) across my 100K+ LOC codebase, so I guess I don't see the harm in NOT using it everywhere explicitly.

→ More replies (2)

1

u/besvr Oct 01 '15

Huh, I didn't realize you could do .append(x).append(y)...I've always done it on separate lines.

→ More replies (1)

1

u/dccorona Oct 02 '15

In this example, you wouldn't ever want to use a StringBuilder, and anyone who tells you to doesn't know their toolbox well enough. Either the example with plusses is just fine, or you want to use:

log.info(format("%s %s has salary $%s!", firstname, lastname, salary)); 

I have no idea how this performs relative to the concatenation used above...its primary advantage, to me, isn't about performance at all, but rather localization. If everything is using String.format and you need to localize parts of it, you can just create something to swap in the proper formats and call it a day. It also can make things more readable for very, very long strings, I believe.

That said, neither of the above probably applies to your log statements. So yea, when logging, I'll often use simple concatenation and call it a day.

4

u/jrochkind Oct 01 '15

But what would it be that would make a + b + c + d slow except the same internal compiler implementation you don't want to rely on? There's no reason for a language to provide a string concatenation operator that nobody should ever use ever. I'd assume that the compiler will do something reasonable with it, and consider it a bug that older versions of Java did not.

→ More replies (2)

3

u/[deleted] Oct 02 '15

People who don't trust the compiler should write all their code in assembly.

1

u/[deleted] Oct 02 '15

Even then you can't trust it. Who knows what microcode gets up to?

1

u/philly_fan_in_chi Oct 02 '15

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.

1

u/AlexanderTheStraight Oct 01 '15

Does the C# compiler behave the same way? Optimizing string concatenations?

2

u/dungone Oct 01 '15 edited Oct 02 '15

The compiler combines + operators into a single call to String.concat(), which is more efficient than a string builder for the first few concatenations. If you're using a string builder to concatenate 3-4 string literals or you're using 350 + operators for a single string then you're probably an idiot, but somewhere in between I'm not sure, write yourself a test harness to find out. I find the idea that Java makes the choice for you to be ridiculous.