1

I was learning about use-cases of weakMaps, weakSets and weakRefs.

I came across a code which was written like this:

{
  const x = {
   a: [1, 2]
  };
  var weakMap = new WeakMap();
  weakMap.set(x, 'something');
}
console.log(weakMap);

Note: Please see the console, after running the snippet.

Most of the times, when I run this code, I am getting the key x inside weakMap.

But for couple of times, I got noting inside weakMap, when I used the same code. What is the reason behind it?

I was watching this video for learning.

WeakMap with data in it for above JS code(Codepen).

WeakMap with data

WeakMap without data in it for above JS code(JSFiddle, I could reproduce this only once inside JSFiddle).

WeakMap without data

Is garbage collection unpredictable? I would like to know if you have ever used weakSet, weakMap or WeakRef in real-life coding. In what situation did you use it?

  • 1
    Once your code leaves the outer block, `x` is eligible for garbage collection. Whether it is still in the `weakMap` or not will depend upon whether the GC has cleaned it up yet or not. When exactly the GC gets to it is indeterminate. You should never rely on GC timing for anything. If you put something in a weakMap, you're saying that once it's eligible for garbage collection, it may or may not still be in the weakMap. That's how they work. If it's not eligible for GC because someone else has a full reference to it, then it will remain in the weakMap. – jfriend00 Apr 06 '21 at 00:32
  • 1
    FYI, other than with `console.log()`, you iterate the entire contents of a weakMap anyway. You can only check to see if a specific item is in the map using the `.has()` or `.get()` methods. Once an item is eligible for GC, it's a race condition on whether it's still available in the weakMap or not. It will disappear at some point, but its indeterminate exactly when it disappears. You use the weakMap when you want something to be able to be looked up only when it hasn't otherwise been garbage collected. – jfriend00 Apr 06 '21 at 00:36
  • @jfriend00 You're thinking of weak references there. A `WeakMap` cannot be used with usernames (strings) as keys. – Bergi Apr 06 '21 at 01:35

1 Answers1

1

The difference will depend on when the garbage collector runs in comparison to when you click the WeakMap item in the console to expand it. Take careful note of the warning there:

enter image description here

The items the console shows that exist in the WeakMap are the ones that were in it right when you clicked - not when the console.log line ran.

If the garbage collector ran before you clicked, the x object would be GC'd, and the WeakMap would appear empty.

If the garbage collector did not run before you clicked, the x object would not be GC'd, and the WeakMap would appear populated.

Is garbage collection unpredictable?

In general, yes. Best not to rely on it.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320