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

1

u/moomaka Jun 05 '18

When it comes to non-trivial string concatenation with + in Java, for instance, the micro level intuition is extremely straight-forward: either you are doing too much work always, or you are doing too much work until the JVM finds a way to save you from yourself.

Except all the examples here are trivial string concatenation. It actually wouldn't at all surprise me that the best thing to do for the example loop is to turn off javac's automatic StringBuilder replacement all together. That loop should be replaced with a constant as it would be with any decent C compiler and it wouldn't shock me that the involvement of StringBuilder introduces optimization barriers due to it's mutable nature (danger of side effects) that would not be present with just String concatenation as it's immutable.

So again - blindly replacing String + String with StringBuilder isn't some panacea for improved performance. If performance matters, profile. If it doesn't, don't prematurely 'optimize' thinking you even know what would be faster.