javascript - 使用引用而不是新对象来节省内存和巨大的 GC?

标签 javascript garbage-collection

我需要发起很多关系对象,生命周期很长,数量还在不断增长。

我终于开始深入研究引用,我希望这是我能取得重大胜利的地方(既节省内存又避免巨大的垃圾收集峰值)。


预先初始化对象并使用引用而不是每次都创建新对象是否有意义?

简单示例:

  • 具有属性 birthDate: {day, month} 的 Person 对象
  • 30(天)* 12(月)= 360 如果预先启动可能的对象
  • 1000 人已经创建了 1000 个新的日期对象

我认为在这种情况下它会节省大量(好吧,这是相对的)内存?我对么?

// would this make sense if the # of Persons is so high that
// the probability of all dates being used is close to 100%?
class BirthDate {
  constructor (props) {
    this.day = props.day;
    this.month = props.month;
  }
  // would also be nice to add methods, e.g:
  getAge (currentDateTime) { /* .. */ }
}

let dates = {
  '3.7': new BirthDate({day: 3, month: 7}),
  '4.7': new BirthDate({day: 4, month: 7})
  // etc, 1-30 days for 1-12 months
};

class Person {
  constructor (props) {
    this.id = props.id;
    this.birthDate = props.birthDate;
  }
}

let people = { lookup: {}, array: [] };
for (let i = 0; i < 1000; i++) {
  const person = new Person({
    id: `whatever-${i}`,
    birthDate: {day: 3, month: 7},   // <- new location in memory each time, lots of duplicates
    // birthDate: dates[`${3}.${7}`] // <- should use only reference right?
  });
  people.lookup[person.id] = person;
  people.array.push(person);
}

console.log(people);

最佳答案

答案是是的,您可以通过这种方式在存储方面获得巨大 yield ,最终这也会影响性能。但是有一个问题!如果你有相同的 birthDate对于很多人,您需要编辑 birthDate , 然后改变 birthDate 的一些属性将有效地改变 birthDate其他人都有相同的引用。因此,在我看来,合适的方法是以易于搜索的方式单独存储生日,例如:

{
    //Year
    '1985': {
        //Month
        '07': {'26': {/*Some members*/}}
    }
}

并编写一些函数,使您能够搜索/添加/编辑/删除值,因此,如果您要更改某人的 birthDate ,您只需搜索 birthDate上面这个对象中的引用。如果没有找到,然后创建,所以你最终会得到一个实际的 birthDate ,您可以将其作为已编辑的 birtDate 分配给此人,如无必要,不影响其他人。

关于javascript - 使用引用而不是新对象来节省内存和巨大的 GC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59225016/

相关文章:

java - 有没有人发现垃圾收集调整很有用?

java - 垃圾收集和线程

java - GC 优化 : for vs foreach

用户闲置一段时间后 Javascript 被禁用

javascript - 在同一个 iframe 上打开 HTTPS 网站

javascript - 如何从 KnockoutJS 中的组件节点获取组件的 View 模型

javascript - 如何在 Controller 上获取 $q promise 值

javascript - 使用类名在 JavaScript 中切换回操作

c - 为什么 GC 中的白色/灰色/黑色?

garbage-collection - 默认情况下,Go 中哪些对象是最终确定的,它有哪些陷阱?