Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 389
JackWM Avatar asked Oct 15 '12 16:10

JackWM


People also ask

Which is the efficient way of concatenating the string in Java?

Using StringBuilder or StringBuffer StringBuilder is a widely used and recommended way to concatenate two strings in Java. It is mutable, unlike string, meaning that we can change the value of the object.

Can you use += for strings?

Use the += operator and the concat() method to append things to Strings. operator, these operators are handy for assembling longer strings from a combination of data objects.

Which is the fastest way to concatenate many strings in Java?

concat will typically be the fastest way to concat two String s (but do note null s).


1 Answers

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"
like image 117
Damian Leszczyński - Vash Avatar answered Sep 22 '22 12:09

Damian Leszczyński - Vash