在Java中,如何更有效地追加一个字符串? [英] In Java, how to append a string more efficiently?
问题描述
我写了一个Java程序,其中,我需要追加一个字符串
I wrote a Java program, in which, I need to append a string
u13a2
到现有的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;
或
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?
推荐答案
使用<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html\"><$c$c>StringBuilder$c$c>类。它是什么,你正在尝试做的更有效率。
Use StringBuilder
class. It is more efficient at what you are trying to do.
这篇关于在Java中,如何更有效地追加一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!