0

So WeakMap is weak over the keys... what if I would have two WeakMaps that both store DOM Elements as key with some different values. Let's assume, that we cannot combine them...

If we would remove the DOM Element from the DOM, that would mean that at some point, the (key, value) pair would be removed from the WeakMap, right?

Would that still work, if there are two WeakMaps? Or do they stop each other from removing it?

Fabian
  • 119
  • 3
  • 9

1 Answers1

1

If both WeakMaps hold the same element as a key, then yes, once the element gets removed from the DOM, the garbage collector will be free to remove it from both WeakMaps.

The only problem would be if the WeakMaps held a circular reference to the element somehow: Nope, like Bergi says, circular references in different WeakMaps get garbage collected fine, see https://jsfiddle.net/qzj5mxgL/ for an example. I must include the code as an example for SE to allow me to edit the answer, so:

const delay = ms => new Promise(res => setTimeout(res, ms));
Promise.resolve()
  .then(async () => {
    const map1 = new WeakMap();
    const map2 = new WeakMap();
    console.log('not populated yet, check mem usage for jshell.net');
    await delay(5000);
    for (let i = 0; i < 1e5; i++) {
      const elm1 = document.createElement('div');
      const elm2 = document.createElement('div');
      map1.set(elm1, elm2);
      map1.set(elm2, elm1);
    }
    console.log('populated, check mem usage');
    await delay(5000);
    console.log('done, check mem usage');
    return [map1, map2];
  })
  .then(async (maps) => {
    await delay(1e9);
  });

results in memory usage increasing, then staying high, then decreasing - they do get GCd despite the circular reference.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    Garbage collectors can deal with circular references just fine. If none of the dom elements is referenced from anywhere else, both will get garbage-collected. – Bergi Oct 24 '20 at 17:51
  • Cool, I was hoping to hear that! Is there a way to test the behaviour? Automatic gc is not happening fast/ or at all with a powerful machine. – Fabian Oct 24 '20 at 17:53
  • Bergi may well be right, I'm not sure. I'm going to run some code and test memory usage – CertainPerformance Oct 24 '20 at 17:54
  • @Fabian You can manually trigger gc from the debugger – Bergi Oct 24 '20 at 17:55
  • @Bergi Can you tell me how / send me link, please? – Fabian Oct 24 '20 at 17:58
  • 1
    @Fabian For chrome, https://developers.google.com/web/tools/chrome-devtools/memory-problems. Other browsers' devtools I'd expect to work similar – Bergi Oct 24 '20 at 18:00