+ 2
Which way of appending to a string is more optimal?
I heard this statement from competitive programmer, that is, Appending to a string as str += str2 is far more optimal than str = str + str2, because the latter creates a new string and then replaces its version stored in str. Is this true? If yes, then why? Please give the explanation in simple terms.
31 Antworten
+ 5
I think this is true.
+ 3
~ swim ~ and yeah thanks for clearing things out and giving me time. You seem to be a guy always out there to help someone and not someone who is not very welcoming.
+ 3
From what I understand you'll just end up creating multiple objects when adding strings together and should instead use something like StringBuilder 🤷♂️
+ 3
str+=str2 and str=str+str2 is equivalent, so there is no difference between this two variants
String is immutable in java and in any way you are creating new strings
If you want to build some String from many strings then it is better to use StringBuffer or StringBuilder
+ 2
~ swim ~ Yo! I get it now, thanks :)
+ 2
Oh! You could be right
+ 2
~ swim ~ btw is it only me or you also feel facing some difficulty when different websites use different words(technical terms) but they mean the same. And also while reading official docs.
+ 2
Hmm. But still do you struggle while reading docs thats been regarded as difficult to perceive?
+ 2
Oh! Boosted my confidence! Was feeling so low lately after reading some docs of certain topic.
+ 1
Prometheus 🇸🇬 why bro?
+ 1
For me this is nothing but a syntactic sugar for the latter.
+ 1
~ swim ~ Bro, i didn't get whats inplace in this context. Can you give me an example?
+ 1
~ swim ~ over somewhere, i guess.
+ 1
~ swim ~ maybe thats why string references are immutable in java?
+ 1
So in short, when we use former way, there are two variables playing, and in the latter, there are actually three variables doing the thing, i.e, str, str2, temporary(that gets stored in string pool), am i right?
+ 1
Didn't I mention Java? Oh! I am so sorry
+ 1
~ swim ~ oh! My bad. Btw isnt a string reference a concept in c++ as well?
0
append() of class String is more optimal only if the variables aren't initialized.
Otherwise, str+= str2 is better if the variables are already initialized