In Java, how to append a string more efficiently?
This question already has an answer here:
Use StringBuilder
class. It is more efficient at what you are trying to do.
You should use the StringBuilder class.
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Some text");
stringBuilder.append("Some text");
stringBuilder.append("Some text");
String finalString = stringBuilder.toString();
In addition, please visit:
You can use StringBuffer
or StringBuilder
for this. Both are for dynamic string manipulation. StringBuffer
is thread-safe where as StringBuilder
is not.
Use StringBuffer
in a multi-thread environment. But if it is single threaded StringBuilder
is recommended and it is much faster than StringBuffer
.
上一篇: Stringbuffer,Stringbuilder何时使用?
下一篇: 在Java中,如何更有效地附加字符串?