代码之家  ›  专栏  ›  技术社区  ›  Solo

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

  •  1
  • Solo  · 技术社区  · 4 年前

    我需要启动许多关系对象,生命周期相当长,数量不断增长。

    我终于开始了对引用的深入研究,我希望这是我可以获得巨大成功的地方(既可以节省内存,又可以避免巨大的垃圾收集峰值)。


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

    简单示例:

    • 有财产的人物 birthDate: {day, month}
    • 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);
    1 回复  |  直到 4 年前
        1
  •  1
  •   Lajos Arpad    4 年前

    答案是 ,您可以通过这种方式在存储方面获得巨大收益,最终这也会影响性能。但有一个陷阱。如果你有相同的 birthDate 对于很多人,你需要编辑 出生日期 ,然后更改 出生日期 将有效地改变 出生日期 其他人都有相同的参考。因此,在我看来,适当的方法是以一种易于搜索的方式分别存储生日,例如:

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

    并编写一些函数,使您能够搜索/添加/编辑/删除值,因此,如果要更改某人的 出生日期 ,你只需搜索 出生日期 上面这个对象中的引用。如果找不到,则创建一个 出生日期 ,您可以将其指定给已编辑的 birtDate ,如果没有必要,不会影响其他人。