字符串连接 OutOfMemoryError

String concatenation OutOfMemoryError

我正在摆弄 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 OS 并且没有额外的参数,例如 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

只是一个数学题:

pow(2, 20) 远大于几千。 该字符串有 5 个字符长,您在每个循环步骤中将其加倍。 20 步后,您的字符串(不附加 "newString" 字符串)为 5*pow(2,20) 长。这是 5 242 880 个字符的长度,比第一个循环中的 5+9*1000 = 45000 个字符多得多。

EDIT 通过更正:在第二个循环中你有 5*pow(2,20) + 9*sum(pow(2,i),i,0, 19).