DEV Community

mixbo
mixbo

Posted on

3

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 :)

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay