What's the difference between using chained append and using multiple + to concatenate [duplicate]

家住魔仙堡 提交于 2021-01-07 03:21:35

问题


Am trying to append multiple strings in StringBuilder,
is there any major difference using

String str1 = "some";
String str2 = "string";

Now,

sb.append(str1).append(str2); // using chained appends

and using

sb.append(str1 + str2); // using '+' operator

My IDE suggests me to use the first method, is there difference between them regarding being thread safe or something like that?


回答1:


Under the hood, the Compiler replaces String concatenation with StringBuilder.append, but there are limits. Inside of loops, it creates a new StringBuilder for every iteration, calls toString and appends it to the outside StringBuilder. The same goes for method calls as it needs a value for the method call. After compilation your second version would read

sb.append(new StringBuilder().append(str1).append(str2).toString);

which is obviously not optimal, whereas the first version remains unchanged.




回答2:


Your first method will not create any object except for already created 3 objects. However, second approach will unnecessarily first crate another object for string (str1 + str2) and then append to your StringBuilder object.

First approach is better than second approach.




回答3:


The point of using StringBuilder is to avoid creating unnecessary String objects. String in Java is unmodifiable, which means every time you concatenate two Strings third one is created. For example following code

String concatenation = str1 + str2 + str3;

results in creating unnecessary String str1 + str2, to which then str3 is added and their result is being assigned to "concatenation".

StringBuilder allows you to put all the String you want to concatenate, without creating intermediate objects. Then when you are ready, you build final result.

You should use StringBuilder if you concatenate multiple Strings in a loop. If you want to concatenate just few Strings, you shouldn't use StringBuilder, as cost of it's creation is bigger than cost of intermediate Strings. By writing something like this

sb.append(str1 + str2);

you are obviously missing the point of StringBuilder. Either you do it only for these two Strings, which means you unnecessary create StringBuilder object or you do it in a loop, which means you unnecessary create intermediate str1 + str2 objects.



来源:https://stackoverflow.com/questions/60595405/whats-the-difference-between-using-chained-append-and-using-multiple-to-conca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!