In Java, how to append a string more efficiently? [duplicate]

I wrote a Java program, in which, I need to append a string

" u13a2" to an existing one "u1234 u12de u1386 ... u15a3".

So gradually the string becomes longer and longer. I found the time spent on each appending also becomes longer and longer. Is there any way that we can improve this to some extend ?

The implementation came to my mind includes:

unicodeArray += " "+unicode;

or

unicodeArray = unicodeArray.concat(" "+unicode);

They gave similar performance. I think the main reason that causes these bad performance is the special type String. It creates a new object for every assignment. If you also think so, does this mean I'd better use another type, like byte array?


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"

Use StringBuilder class. It is more efficient at what you are trying to do.


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.


- Each time you append or do any modification with it, it creates a new String object.

- So use append() method of StringBuilder(If thread safety is not important), else use StringBuffer(If thread safety is important.), that will be efficient way to do it.