简体   繁体   English

Node.js上奇怪的内存使用情况

[英]Weird memory usage on Node.js

This simple code stores 1 million strings (100 chars length) in an array. 这个简单的代码在一个数组中存储了100万个字符串(100个字符长度)。

function makestring(len) {
    var s = '';
    while (len--) s = s+'1';
    return s;
}

var s = '';
var arr = [];
for (var i=0; i<1000000; i++) {
    s = makestring(100);
    arr.push(s);
    if (i%1000 == 0) console.log(i+' - '+s);
}

When I run it, I get this error: 当我运行它时,我收到此错误:

(...)
408000 - 1111111111111111111 (...)
409000 - 1111111111111111111 (...)
FATAL ERROR: JS Allocation failed - process out of memory

That's strange 1 million * 100 are just 100 megabytes. 奇怪的是,100万* 100只是100兆字节。

But if I move the s = makestring(100); 但是如果我移动s = makestring(100); outside the loop... 循环之外......

var s = makestring(100);
var arr = [];
for (var i=0; i<1000000; i++) {
    arr.push(s);
    if (i%1000 == 0) {
        console.log(i+' - '+s);
    }
}

This executes without errors! 执行没有错误!

Why? 为什么? How can I store 1 Million objects in node? 如何在节点中存储1百万个对象?

In the moment you move the String generation outside the loop, you basically just create one String and push it a million times into the array. 在您将循环外的String生成移动的那一刻,您基本上只需创建一个String并将其推入数组一百万次。

Inside the array, however, just pointers to the original String are used, which is far less memory consuming then saving the String a million times. 但是,在数组内部,只使用指向原始String的指针,这比消耗字符串一百万次要少得多。

Your first example builds 1000000 strings. 您的第一个示例构建1000000字符串。

In your second example, you're taking the same string object and adding it to your array 1000000 times. 在第二个示例中,您将使用相同的字符串对象并将其添加到阵列1000000次。 (it's not copying the string; each entry of the array points to the same object) (它不是复制字符串;数组的每个条目都指向同一个对象)

V8 does a lot of things to optimize string use. V8做了很多事情来优化字符串的使用。 For example, string concatenation is less expensive (in most cases) than you think. 例如,字符串连接比您想象的要便宜(在大多数情况下)。 Rather than building a whole new string, it will typically opt to connect them ia linked list fashion under the covers. 它不是构建一个全新的字符串,而是选择以链接列表方式连接它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM