在Java中,如何更有效地附加字符串? [英] In Java, how to append a string more efficiently?

查看:23
本文介绍了在Java中,如何更有效地附加字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个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 ?

我想到的实现包括:

unicodeArray += " "+unicode;

unicodeArray = unicodeArray.concat(" "+unicode);

他们的表现相似.我认为导致这些糟糕性能的主要原因是特殊类型String.它为每个分配创建一个新对象.如果你也这么认为,这是否意味着我最好使用另一种类型,比如字节数组?

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?

推荐答案

使用 StringBuilder 类.它在您尝试做的事情上更有效率.

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

这篇关于在Java中,如何更有效地附加字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆