我正在摆弄 Java.lang.String 并在它们上使用“+”运算符。我很好奇为什么会得到以下输出:
使用下面的代码,我可以获得数千次迭代并且不会引发内存异常:
public static void main(String[] args) {
String str = "hello";
int count = 1;
while (true) {
System.out.println(count++);
str = str + "newString";
}
}
但是,当我将“str”添加到自身时,在 20-30 次迭代后,我收到 OutOfMemoryError 异常:
public static void main(String[] args) {
String str = "hello";
int count = 1;
while (true) {
System.out.println(count++);
str = str + "newString" +str;
}
}
我在 32 位操作系统上使用 eclipse,没有额外的参数,例如 Xms 或 Xmx
最佳答案
如果你这样做
str = str + "newString";
您的字符串在每次迭代中线性增长 9 个字符。
Iteration String length
1 5
2 14
3 23
4 32
5 41
6 50
...
30 266
另一方面,如果你这样做
str = str + "newString" + str;
你的字符串呈指数增长。每次迭代它都会变成两倍长 + 9 个字符。
Iteration String length
1 5
2 19
3 47
4 103
5 215
6 439
...
30 7516192759
关于java - 字符串连接OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31870127/