问题
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:
- Mutable
- Not Synchronized.
来源:https://stackoverflow.com/questions/18467989/when-is-stringbuilder-is-preferred-instead-appending-string-to-string