问题描述
我在一个循环中连接一个字符串,但它需要很长时间,为什么呢?
I am concatenating a String in a loop but it takes ages, why is that?
for (String object : jsonData) {
counter++;
finalJsonDataStr += object;
}
变量对象
是一段JSON,最多70个字符,循环大约50k次。
Variable object
is a piece of JSON, up to 70 chars and the loop goes approx 50k times.
我理解一些人的建议 StringBuffer
或 StringBuilder
但是这个链接说,它没有性能改进:
I understand some people advice StringBuffer
or StringBuilder
but this link says, it has no performance improvements: StringBuilder vs String concatenation in toString() in Java
推荐答案
使用字符串生成器附加到字符串。
Use a String Builder to append to strings.
连接时,Java实际上是创建一个带有连接结果的新String。
多次这样做,你无所事事地创造了大量的字符串。
When you concatenate, Java is actually creating a new String with the results of the concatenation.Do it multiple times and you are creating gazillion of strings for nothing.
尝试:
StringBuilder sb = new StringBuilder();
for (String object : jsonData) {
counter++;
sb.append(object.toString()); //this does the concatenation internally
//but is very efficient
}
finalJsonDataStr = sb.toString(); //this gives you back the whole string
备注:
当你做类似的事情时
myString = "hello " + someStringVariable + " World!" + " My name is " + name;
编译器足够聪明,用一个 StringBuilder替换所有这些 code>,如:
The compiler is smart enough to replace all that with a single StringBuilder
, like:
myString = new StringBuilder("hello ")
.append(someStringVariable)
.append(" World!")
.append(" My name is ")
.append(name).toString();
但由于某些原因我不知道,当连接发生时,它不会这样做一个循环。
But for some reason I don't know, it doesn't do it when the concatenation happens inside a loop.
这篇关于为什么字符串连接需要这么长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!