Node.js 销毁嵌套在数组中的对象
我在一个循环中填充了一个嵌套对象数组 比如:Node.js 销毁嵌套在数组中的对象,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 = _.cloneD
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);
}
}
函数getNestedObject(i){
//一些对象创建代码
}
对于(i=0;i<50000;i++){
var item=uu.cloneDeep(getNestedObject(i));
myArray.push(项目);
如果(myArray.length>20){
//删除所有元素并从头开始推送
//我是否需要额外销毁这20个被覆盖对象中的每个对象,以避免内存溢出?
myArray.拼接(0,20);
}
}
这是避免由于对象数组占用堆空间而导致堆溢出所必需的
我是否需要额外销毁这20个被覆盖对象中的每个对象中的项目,以避免内存溢出或在此范围内发生自动gc?我不确定数组中的实际对象有多大,但您可以尝试lodash
chunk
方法将数组划分为具有指定长度的多个数组如果您已经有一个对象数组,如下所示
要做到这一点,请使用方法
现在,回答你关于进程内存的问题是,如果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
尝试将拆分数组写入临时文件,并在需要时将其读回。
对于(i=0;i<50000;i++){
var item=uu.cloneDeep(getNestedObject(i));
myArray.push(项目);
如果(myArray.length>20){
//和数组临时文件
writeFileSync('myTemp.json',json',utf8');
//清除临时数组
myArray=[];
}
//在这一点上,内存中没有任何异常
}
注*以上为伪代码,解释可能需要根据要求进行更改
我想补充一点,根据您计划何时使用这些对象或在逻辑中处理它们,解决方案可能会有所不同
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