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

Use references instead of new objects to save memory and huge GC?

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

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


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

简单示例:

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

// 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[`.`] // <- should use only reference right?
  });
  people.lookup[person.id] = person;
  people.array.push(person);
}

console.log(people);

答案是,您可以通过这种方式在存储方面获得巨大收益,最终这也会影响性能。但是有一个问题!如果您对许多人有相同的 birthDate,并且您需要编辑一个 birthDate,那么更改 birthDate 的某些属性将有效地改变 birthDate 其他拥有相同的人参考。因此,在我看来,合适的方法是以易于搜索的方式单独存储生日,例如:

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

并编写一些使您能够 search/add/edit/remove 值的函数,因此,如果您要更改某人的 birthDate,您只需在上面的这个对象中搜索那个 birthDate 引用.如果找不到,然后创建,所以你最终会得到一个实际的 birthDate,你可以将其分配给编辑后的人 birtDate,如果不需要,不会影响其他人。