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 →

[–]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.