字符串连接OutOfMemoryError

dpa*_*shu 0 java memory-leaks memory-management

我正在摆弄Java.lang.String并在它们上使用'+'运算符.我很想知道为什么获得以下输出:

使用下面的代码,我可以获得数千次迭代,并且不会抛出任何内存异常:

public static void main(String[] args) {
        String str = "hello";
        int count = 1;
        while (true) {
            System.out.println(count++);
            str = str + "newString";
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我将'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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我在32位操作系统上使用eclipse而没有额外的args,如Xms或Xmx

Rob*_*sen 6

如果你这样做

str = str + "newString";
Run Code Online (Sandbox Code Playgroud)

你的字符串在每次迭代时线性增长9个字符.

Iteration    String length
1            5
2            14
3            23
4            32
5            41
6            50
...
30           266
Run Code Online (Sandbox Code Playgroud)

另一方面,如果你这样做

str = str + "newString" + str;
Run Code Online (Sandbox Code Playgroud)

你的字符串呈指数增长.它在每次迭代时变为两倍+9个字符.

Iteration    String length
1            5
2            19
3            47
4            103
5            215
6            439
...
30           7516192759
Run Code Online (Sandbox Code Playgroud)