I've run across a JavaScript library that implement a cross-browser WeakMap in ES5. (WeakMap is slated for ES6.)
How can this possibly work without support in the JavaScript language itself?
Just to be clear, I'm referring to a Weak Map, not a regular Map. I tested this project out using Chrome's profiler and the keys are not held by strong references. They get GC'ed without having to remove them from the WeakMap.
I've run across a JavaScript library that implement a cross-browser WeakMap in ES5. (WeakMap is slated for ES6.)
How can this possibly work without support in the JavaScript language itself?
Just to be clear, I'm referring to a Weak Map, not a regular Map. I tested this project out using Chrome's profiler and the keys are not held by strong references. They get GC'ed without having to remove them from the WeakMap.
Share Improve this question edited Dec 25, 2024 at 21:54 dumbass 27.2k4 gold badges36 silver badges73 bronze badges asked May 3, 2013 at 19:12 paleozogtpaleozogt 6,56311 gold badges54 silver badges97 bronze badges 3- 3 Consider studying the source code. – user1106925 Commented May 3, 2013 at 19:17
- 4 @squint It's doing something fairly deep-- I can't figure out how its not holding a strong reference to the keys. It's not using Arrays, for example. – paleozogt Commented May 3, 2013 at 21:08
- 5 WeakMaps are an ES6 feature that allows you to associate data with an object, but still let that data be garbage collected when either the object -OR- the WeakMap instance itself is garbage collected. It's impossible to do both of these without language support. Most WeakMap shims ignore the part about letting the data be GC'd when the WeakMap instance itself is GC'd. – Macil Commented Dec 22, 2014 at 23:23
1 Answer
Reset to default 37It took me a while to grok the code, but then it hit me: the key itself is used to store a reference to the value.
For example, several layers into set
it does
defProp(obj, globalID, { value: store });
where defProp
has been defined to be Object.defineProperty
, obj
is the key, globalID
is a guid and store
is a storage object that contains the value.
Then down in get
it looks up the value with
obj[globalID];
This is very clever. The WeakMap doesn't actually contain a reference to anything (weak or otherwise)-- it just sets up a policy of where to secretly store the value. The use of Object.defineProperty
means that you won't accidentally discover the value storage-- you have to know the magic guid to look it up.
Since the key directly refers to the value (and the WeakMap doesn't refer to it), when all references to the key are gone, it gets GCed like normal.