node.js - 销毁数组中嵌套的对象

标签 node.js

我有一个循环填充的嵌套对象数组。

类似于:

var myArray = [
   object1: {
       //lots of nesting
   },
   ...
]

现在我对此运行一个循环,并希望在每次循环迭代后从索引 1 开始覆盖,例如:

function getNestedObject(i) {
    //some object creation code
}

for (i = 0 ; i< 50000 ; i++) {
    var item = _.cloneDeep(getNestedObject(i));
    myArray.push (item);
    if (myArray.length > 20) {
        //delete all elements and start pushing from scratch
        //Do i need to additionally destroy the items within each of these 20 objects being overwritten to avoid memory overflow?
        myArray.splice(0,20);
    }
}

这是为了避免由于堆空间被对象数组吞噬而导致堆溢出所必需的。

我是否需要另外销毁这 20 个被覆盖对象中的每一个对象,以避免内存溢出或在此范围内发生自动垃圾回收?

最佳答案

我不确定数组中的实际对象有多大,但如果您已经有一个数组,您可以尝试使用 lodash chunk 方法将数组分成多个具有指定长度的数组 的对象如下所示。

为此,请使用 lodash chunk方法。

_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]

_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]

_.chunk(myArray, 20);
// [[arr1],[arr2] ... ]
// This will produce your resultantn arrays
<小时/>

现在,要回答关于进程内存的问题是,如果 myArray 的大小变得很大,并且您将其拆分为大小为 20 的较小数组。 在创建数组的过程中,即使您删除或拼接原始数组,在拆分过程结束时,内存中仍然保留着已拆分的对象,因此不存在削减成本可以这么说。您可能仍然会遇到内存溢出

Try writing the split arrays to a temp file and read it back when needed.


    for (i = 0 ; i< 50000 ; i++) {
        var item = _.cloneDeep(getNestedObject(i));
        myArray.push (item);
        if (myArray.length > 20) {  
            //appeand the array temp file
            fs.writeFileSync('myTemp.json', json, 'utf8');
            //clear the temp array
            myArray = [];
        }
        //nothing subastanital in memory at this point
     }

note* above is pseudo code for explanation may need to change as per requirements

我想补充的是,解决方案可能会有所不同,具体取决于您计划何时使用这些对象或在逻辑中处理它们。

关于node.js - 销毁数组中嵌套的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49554653/

相关文章:

JavaScript .replace() 只替换最后一个匹配项?

node.js - 如何填充子文档的引用 (Mongoose)

javascript - Node.js 和前端 js 返回不同的日期格式

javascript - 无法使用 Node.js 更新 Mysql 数据库

node.js - 在 Mongoose 中如何声明动态 Schema

node.js - 为什么 mongo 不返回所有字段?

node.js - 如何删除filepond上的临时上传文件

node.js - RabbitMQ 是否有相当于 "ping"的值?如何诊断交换器或队列是否正在广播?

javascript - Grunt less 文件观察器

javascript - 将 camunda dmn modeler 集成到 spring mvc 应用程序中与 Angular js 前端