Java String vs StringBuilder [英] Java String vs StringBuilder
问题描述
据我所知Java字符串中的 +运算符
重载,并且当我们使用 +
运算符时,它会自动选择StringBuffer或StringBuilder来连接具有更好性能的字符串.唯一的例外是在循环中使用 +
运算符时.在这种情况下,Java不使用StringBuffer和StringBuilder的好处.真的吗?我将连接40个字符串(大约4500个字符),并且我会经常重复它,所以我想确定一下.
As far as i know + operator
in Java String is overloaded and while we are using +
operator it automatically chooses StringBuffer or StringBuilder to concatenate strings with better performance. Only exception of this is while we are using +
operator inside a loop. In this case Java doesn't use benefits of StringBuffer and StringBuilder. Is that true? I will concatenate 40 Strings (around 4500 chars) and I will repeat it so often so I wanted be sure about it.
推荐答案
不,Java会总是(ss总是)(几乎总是在下面的注释中)将串联转换为 StringBuilder
.但是,循环的问题在于,它将在每个演练中创建 StringBuilder
的新实例.
No, Java will always (almost always, see comment bellow) convert concatenation into the StringBuilder
. However the problem with loop is that it will create new instance of StringBuilder
per each walkthrough.
因此,如果您在从 0
到 1000
的循环中执行 String someString = i +"something";
您新的 StringBuilder
实例1000次.那么这可能是性能问题.因此,只需在循环之前声明 StringBuilder
,然后在循环内部使用它即可.
So if you do String someString = i + "something";
inside the loop which goes from 0
to 1000
it will create for you new instance of StringBuilder
1000 times. Which could be a performance problem then. So just declare StringBuilder
before the loop and then use it inside it.
这篇关于Java String vs StringBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!