ECMAScript 6 introduces weak maps, available in Node.JS v0.11.3 with the --harmony
flag. Consider the following.
let weakMap = WeakMap();
let key = [];
let rubbish = 'fish cans';
weakMap.set(key, rubbish);
rubbish = 'empty bottle';
// Prints "fish cans"
console.log(weakMap.get(key));
I was under the impression that, for weak maps, the reference from the key to the value is weak, so that if the only reference to the value is the key, then the value can no longer be accessed.
Why then is the value 'fish cans'
still accessible and not garbage collected? The variable rubbish
no longer references it, and the reference from key
to 'fish cans'
is weak, i.e. non-existant from the point of view of the garbage collector. What am I missing?
The weak part is about the keys, not the values. From the current draft:
WeakMap are intended to provide a mechanism for dynamically associating state with an object in a manner that does not “leak” memory resources if, in the absence of the WeakMap, the object otherwise became inaccessible and subject to resource reclamation by the implementation’s garbage collection mechanisms.
Say you have a DOM element and want to associate some data with it and use a WeakMap
for that: weakMap.set(domElement, data);
. When the DOM element gets deleted then the entry in the weak map gets deleted too.
On the other hand you would not want the data to be deleted as long the DOM element exists, just because there is no other reference to it outside the weak map.
Apart from that 'fish cans'
is a primitive type and as such not subject to the garbage collection.