In Java, how to append a string more efficiently?

This question already has an answer here:

  • Difference between StringBuilder and StringBuffer 31 answers

  • 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:

  • "How Java optimize the code with StringBuilder?"
  • "StringBuilder vs String concatenation in toString() in Java"

  • 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 .

    链接地址: http://www.djcxy.com/p/72334.html

    上一篇: Stringbuffer,Stringbuilder何时使用?

    下一篇: 在Java中,如何更有效地附加字符串?