50

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?

LarsH
  • 27,481
  • 8
  • 94
  • 152
JackWM
  • 10,085
  • 22
  • 65
  • 92

5 Answers5

109

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:

Community
  • 1
  • 1
35

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

Pradeep Pati
  • 5,779
  • 3
  • 29
  • 43
8

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
2

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

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
0

java.lang.StringBuilder. Use int constructor to create an initial size.

Jeff Miller
  • 1,424
  • 1
  • 10
  • 19