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?
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.
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.
concat will typically be the fastest way to concat two String s (but do note null s).
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With