54

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?

4
  • 3
    Related: en.wikipedia.org/wiki/Schlemiel_the_Painter%27s_algorithm Commented Oct 15, 2012 at 16:34
  • 9
    How many duplicate StringBuilder answers do we need? Commented Oct 15, 2012 at 16:51
  • 2
    @SteveKuo Voting to close this redundant question is quicker than posting a complaint. Commented Aug 29, 2014 at 3:36
  • Awesome link, @OrangeDog Commented Aug 29, 2014 at 5:50

5 Answers 5

115

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:

Sign up to request clarification or add additional context in comments.

Comments

36

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

Comments

9

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.

4 Comments

StringBuffer is thread-safe as well. see docs.oracle.com/javase/1.5.0/docs/api/java/lang/…
It is the way round: StringBuilder is NOT thread safe whereas StringBuffer is.
But who manipulates a single CharSequence in a concurrent threads? I believe StringBuffer's thread-safety has no usage.
Its all depend upon requirement.
3

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.