Search code examples
javascriptgarbage-collectionecmascript-6weakmap

Timing issues considerations when using WeakMap from EcmaScript


What is the proper usage of the WeakMap in JavaScript? What kind of timing issues may occur when I use it? IN particular, I am wondering what would happen in the following situation:

var wm1 = new WeakMap()
var o1 = {},
o2 = function(){},
o3 = window;
// in other method:
    wm1.set(o1, 37);
    wm1.set(o2, "azerty");
    if (wm1.has(o2)) {
    //Garbage collection happen here, objects from wm1 may no longer exists
    Console.log(wm1.get(o2)) // what will happen here? just undefined? null?
    }

how GC will affect WeakMaps?

Update: my bad, I missed the fact that you can't have string as keys in WeakMap, my question does not make if I take into account that fact.


Solution

  • WeakMaps are explicitly designed to not exhibit the least observable garbage collection behaviour. There will be absolutely zero issues.

    In your specific situtation, as long as you hold a reference to the object or to the function (through the live variables o1 and o2 that are still on the stack), you will be able to find them in the WeakMap or WeakSet. As soon as you don't hold a reference to them any more, and nobody does, they are eligible for garbage collection (just as usual) - and given that, nobody will be able to try to look them up in the collection.