48

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
  • 26,606
  • 8
  • 88
  • 145
JackWM
  • 9,467
  • 21
  • 61
  • 91

5 Answers5

107

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,670
  • 2
  • 28
  • 42
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
  • 310,138
  • 72
  • 642
  • 762
Subhrajyoti Majumder
  • 39,719
  • 12
  • 74
  • 101
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
  • 32,904
  • 6
  • 47
  • 76
0

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

Jeff Miller
  • 1,384
  • 1
  • 9
  • 19