Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WeakMap implementation in EcmaScript5?

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?

Edit: 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.

like image 319
paleozogt Avatar asked May 03 '13 19:05

paleozogt


People also ask

What is WeakMap used for?

WeakMap is Map -like collection that allows only objects as keys and removes them together with associated value once they become inaccessible by other means. WeakSet is Set -like collection that stores only objects and removes them once they become inaccessible by other means.

What is the difference between a WeakMap and a Map?

Differences between Map and WeakMap 1) A WeakMap accepts only objects as keys whereas a Map,in addition to objects, accepts primitive datatype such as strings, numbers etc. 2) WeakMap objects doesn't avert garbage collection if there are no references to the object which is acting like a key.


1 Answers

It 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.

like image 156
paleozogt Avatar answered Nov 10 '22 04:11

paleozogt