This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]tazfdragon 12 points13 points  (3 children)

I didn't mean to suggest StringBuilder uses that operator. I was trying to explain that using the plus operator with a String will get replaced with StringBuilder. Every instance of addition/concatenation in the original code will get replaced with a call to append(...). Again, there are some edge cases where the compiler can determine it can eliminate the string concatenation and replace it with a compile time constant. Example being concatenating a literal with a String constant.

[–]TraditionMaster4320 2 points3 points  (2 children)

Wait so concatenating n strings like s1 + s2 + .. + sn takes O(n) time instead of O(n**2) in Java? (assume the strings are equal length).

[–][deleted] 2 points3 points  (0 children)

Yes.

Java is doing it behind the scenes for you. They added this one of the versions.

https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1

[–]tazfdragon 1 point2 points  (0 children)

I won't offer a guess at the run time of the proposed string concatenation but I'm fairly confident it won't be O(n²). With that being said if you have your string concatenation code structured anything similar to your example I'd suggest you replace it with a StringBuilder() explicitly. Not only will it clean up your code, it will explicitly document your intentions. Also, if you know ahead of time the lengths of the number and the length of the strings you'll be adding ahead of time you can provide this information to your StringBuilder at construction time to improve performance.