When is `StringBuilder` is preferred instead appending `String` to `String`? [duplicate]

扶醉桌前 提交于 2019-12-02 13:03:17

问题


Below are two ways how to append String:

String firstString = "text_0";
String secondString = "text_1";
String resultString = firstString + secondString;

StringBuilder sb = new StringBuilder();
sb.append(firstString).append(secondString);
String resultString = sb.toString();

My question is - when is more effective to use StringBuilder? Let's say there are 10 strings, and I need to create one of them.


回答1:


Because StringBuilder can "append" a string instead of concatenating two strings each time creating a new object. Even if you use += operator with Strings a new object is created. This advantage will only become relevant once you try to concatenate a great number of strings. If is also consiedered a bit more readable.




回答2:


Two main Advantages:

  1. Mutable
  2. Not Synchronized.


来源:https://stackoverflow.com/questions/18467989/when-is-stringbuilder-is-preferred-instead-appending-string-to-string

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