What's the difference between ES6 Map and WeakMap?

前端 未结 7 714
感情败类
感情败类 2020-12-02 06:00

Looking this and this MDN pages it seems like the only difference between Maps and WeakMaps is a missing \"size\" property for WeakMaps. But is this true? What\'s the differ

7条回答
  •  無奈伤痛
    2020-12-02 06:37

    From Javascript.info

    Map -- If we use an object as the key in a regular Map, then while the Map exists, that object exists as well. It occupies memory and may not be garbage collected.

    let john = { name: "John" };
    let array = [ john ];
    john = null; // overwrite the reference
    
    // john is stored inside the array, so it won't be garbage-collected
    // we can get it as array[0]
    

    Similar to that, if we use an object as the key in a regular Map, then while the Map exists, that object exists as well. It occupies memory and may not be garbage collected

    let john = { name: "John" };
    let map = new Map();
    map.set(john, "...");
    john = null; // overwrite the reference
    
    // john is stored inside the map,
    // we can get it by using map.keys()
    

    WeakMap -- Now, if we use an object as the key in it, and there are no other references to that object – it will be removed from memory (and from the map) automatically.

    let john = { name: "John" };
    let weakMap = new WeakMap();
    weakMap.set(john, "...");
    john = null; // overwrite the reference
    
    // john is removed from memory!
    

提交回复
热议问题