r/programming • • Jun 05 '18

Code golfing challenge leads to discovery of string concatenation bug in JDK 9+ compiler

https://stackoverflow.com/questions/50683786/why-does-arrayin-i-give-different-results-in-java-8-and-java-10
2.2k Upvotes

355 comments sorted by

View all comments

Show parent comment

6

u/evaned Jun 05 '18

Coming from a c++ background - I'd expect this to only evaluate once.

Ditto. I was actually initially surprised that people would even think it's evaluated more than once; I think this is probably an illustration of how what languages you know shapes your thinking. (I'm still surprised -- c++ is by no means unique here -- but less so.)

This is super important because otherwise every operation of the form *x+= y would mean x being dereferenced twice.

It's also important because a += b can in fairly realistic scenarios be asymptotically more efficient than a = a + b for some calls. (And will almost always be slightly faster unless the optimizer is able to remove an extra copy that is made with +.)

2

u/f03nix Jun 05 '18

in fairly realistic scenarios be asymptotically more efficient

Absolutely, I mentioned dereference as a simple but super common example, there are certainly more scenarios where the impact is even larger - like increments on a map element map[key]++; .

I think more than languages, this is dependent on how people are taught and view the operators. I mentioned c++ because operator overloading makes you think of += very differently.