javascriptecmascript-6traceur

ECMAScript 6: what is WeakSet for?


The WeakSet is supposed to store elements by weak reference. That is, if an object is not referenced by anything else, it should be cleaned from the WeakSet.

I have written the following test:

var weakset = new WeakSet(),
    numbers = [1, 2, 3];

weakset.add(numbers);
weakset.add({name: "Charlie"});

console.log(weakset);

numbers = undefined;

console.log(weakset);

Even though my [1, 2, 3] array is not referenced by anything, it's not being removed from the WeakSet. The console prints:

WeakSet {[1, 2, 3], Object {name: "Charlie"}}
WeakSet {[1, 2, 3], Object {name: "Charlie"}}

Why is that?

Plus, I have one more question. What is the point of adding objects to WeakSets directly, like this:

weakset.add({name: "Charlie"});

Are those Traceur's glitches or am I missing something?

And finally, what is the practical use of WeakSet if we cannot even iterate through it nor get the current size?


Solution

  • it's not being removed from the WeakSet. Why is that?

    Most likely because the garbage collector has not yet run. However, you say you are using Traceur, so it just might be that they're not properly supported. I wonder how the console can show the contents of a WeakSet anyway.

    What is the point of adding objects to WeakSets directly?

    There is absolutely no point of adding object literals to WeakSets.

    What is the practical use of WeakSet if we cannot even iterate through it nor get the current size?

    All you can get is one bit of information: Is the object (or generically, value) contained in the set?

    This can be useful in situations where you want to "tag" objects without actually mutating them (setting a property on them). Lots of algorithms contain some sort of "if x was already seen" condition (a JSON.stringify cycle detection might be a good example), and when you work with user-provided values the use of a Set/WeakSet would be advisable. The advantage of a WeakSet here is that its contents can be garbage-collected while your algorithm is still running, so it helps to reduce memory consumption (or even prevents leaks) when you are dealing with lots of data that is lazily (possibly even asynchronously) produced.