What's the difference between ES6 Map and WeakMap?

前端 未结 7 740
感情败类
感情败类 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:26

    They both behave differently when a object referenced by their keys/values gets deleted. Lets take the below example code:

    var map = new Map();
    var weakmap = new WeakMap();
    
    (function(){
        var a = {x: 12};
        var b = {y: 12};
    
        map.set(a, 1);
        weakmap.set(b, 2);
    })()
    

    The above IIFE is executed there is no way we can reference {x: 12} and {y: 12} anymore. Garbage collector goes ahead and deletes the key b pointer from “WeakMap” and also removes {y: 12} from memory. But in case of “Map”, the garbage collector doesn’t remove a pointer from “Map” and also doesn’t remove {x: 12} from memory.

    Summary: WeakMap allows garbage collector to do its task but not Map.

    References: http://qnimate.com/difference-between-map-and-weakmap-in-javascript/

提交回复
热议问题