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 without data in it for above JS code(JSFiddle, I could reproduce this only once inside JSFiddle).
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?
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:
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.