I'm exploring the time complexities of string concatenation. I've read on many websites that the time complexity of concatenating two strings using the + operator is O(n^2) (or O(mn) to be exact in regards to concatenating two different string variables). I'm wondering if this only occurs for a certain type of concatenation scheme (using the + operator). I'm contemplating whether:
void append1 (String s){
//s literal is " world"
String str = "hello";
for (int i = 0; i < s.length; i++){
str += s.charAt(i);
}
}
has the same time complexity as:
void append2 (String s){
//s literal is " world"
String str = "hello";
str += s;
}
Would this be true or false?
In append1(String s) I understand that a new concatenation occurs every new iteration, and thus I can see how the time complexity for appending to String str in append1(String s) is O(n^2) i.e. O(mn) in our case (being the old copies are always copied over to a new array that can fit the new additional to-be-added character). However, in append2(String s), is it still the case that a new array, with copying all previous characters into it, is undergone for each character in the RHS literal (which would entail that " world" is not just one concatenation but many for each charAt(x) in " world"?)? For:
str += " world"
Is it not the case that the compiler can detect the length of the RHS literal and directly assign the new array to be whatever the length of str is + the RHS literal right away, or is it unable to do so and just creates the new arrays whenever a new character is to be appended? If this is the case, doesn't this entail that creating any type of String is O(n^2) (if not, how can the compiler infer the length of RHS literal for String x = "hello" (which presumably is O(n)) but not x += " world")? Conclusively, should:
str += " world"
be regarded as one or many concatenations? Thanks.