字符串操作的Nodejs内存不足错误

Nodejs out of memory error with string operations

给定一个字符串 s,将其分配 n 次,长度为 x。示例:如果 n = 7s = "ada",则最终字符串为 adaadaa。最后统计字符串中a的个数。

我的解决方案可以在下面找到。它工作正常,除了在 n = 10000000 或更多时出现 API fatal error handler returned after process out of memory 错误。

这是为什么? javascript 中的字符串操作是什么导致它 运行 内存不足,如果 n=100000 工作正常?它与引擎如何尝试给它一个 int 类型有关,而它应该是一个 long 类型?

const s = "a";
const n = 100000000;

let count = 0;
let output = "";
for (let i = 0; i < n; i++) {
    if (count % s.length == 0) {
        count = 0;
    }
    output += s[count];
    count++;
}

let finalCount = 0;
let arr = output.split('');
for (let i = 0; i < arr.length; i++) {
    if (arr[i] == 'a') {
        finalCount++;
    }
}

console.log(finalCount);

您还可以增加 nodejs 的最大内存大小,它默认设置为 1 GB,请参阅下面的 link 了解如何增加大小。您已达到极限,它是 nodejs 的极限,而不是 javascript。

https://medium.com/@vuongtran/how-to-solve-process-out-of-memory-in-node-js-5f0de8f8464c

另外, 在您的第一个 for 循环中,您有一个 if 语句检查计数(在第一个循环后等于 1)除以 1 的余数是否为 1,如果是,它将计数设置为 0,然后将 'a' 添加到输出,然后将计数设置为 1,使整个循环再次变为 运行。

What is it about string operations in javascript that causes it to run out of memory?

您只是在构建一个巨大的字符串。这样的字符串需要驻留在内存中的某个地方。你的字符串太大了。

您可以优化算法,使其不需要那么大的字符串(在这个特定示例中,我什至认为它也是一个简化):

const s = "a";
const n = 100000000;

let count = 0;
let finalCount = 0;
for (let i = 0; i < n; i++) {
    if (count % s.length == 0) {
        count = 0;
    }
    if (s[count] == 'a') {
        finalCount++;
    }
    count++;
}

console.log(finalCount);

(您可以进一步优化,使其在 n 之前不需要循环,但在 O(s.length) 中运行,但这不是减少内存使用所必需的)。