DEV Community

mixbo
mixbo

Posted on

How to use WeakMap WeakSet in javascript.

Alt Text

Javascript GC will collect object and release space which not used

let obj = { name: "foo" };
obj = null;
// GC will release obj space in memory
Enter fullscreen mode Exit fullscreen mode

But this case will not release space

let obj = { name: "foo" };
let maps = new Map();
maps.set(obj, "obj-value");
obj = null; // set obj to null want to release sapce
maps.get(obj) // 'obj-value'
// maps => Map(1) {{…} => "obj-value"}
Enter fullscreen mode Exit fullscreen mode

Emmm.. we just set null to obj but not release space in memory, we can fetch the value use maps.get(obj) why?

If you want to release obj maybe you can use WeakMap or WeakSet

let weakMap = new WeakMap();
let obj = { name: "foo" };
weakMap.set(obj, "obj-value");
console.log(weakMap.get(obj)) //=> "obj-value"
obj = null
console.log(weakMap.get(obj)) //=> undefined 
Enter fullscreen mode Exit fullscreen mode

I think WeakMap more useful when you need store object key to map , aslo WeakSet too.

Hope it can help you :)

Top comments (0)