0

In MDN article on WeakSets, an example is given for using weak sets to avoid infinite recursion on circular references:

// Execute a callback on everything stored inside an object
function execRecursively(fn, subject, _refs = new WeakSet()) {
  // Avoid infinite recursion
  if (_refs.has(subject)) {
    return;
  }
  // ...

If WeakSet is intended to allow the objects to be garbage collected, doesn’t this mean that with sufficiently large objects and little memory a previously encountered object will be garbage collected and thus set’s .has() will not return true, making infinite recursion possible?

1 Answers1

2

WeakSet only allows garbage collection of objects which are not referenced anywhere else, i.e. if the reference in the WeakSet is the only remaining reference.

If the object is referenced as part of some other data structure, it will not be garbage collected. If that structure gets too big, you will just get an "out of memory"-error.

JacquesB
  • 57,310
  • 21
  • 127
  • 176
  • This would require that in `execRecursively(fn, subject[key], _refs);` line of the example, that `subject` will survive for *all* subsequent (possibly recursing many times) runs of the function… Which I guess would be the case. If so, I can see why weak sets are *acceptable* for this case. – Anton Strogonoff Jul 15 '23 at 08:55
  • I still don’t see why the article says they are “ideal” for this use case: since the code manually deletes the `subject` from the weak set after that recursive call, I can’t see how it is different from using a regular set… – Anton Strogonoff Jul 15 '23 at 08:58
  • 2
    @AntonStrogonoff: You are correct. As far as I can tell, you might just as well have used a regular Set for this. The MDN text alludes to WeakSet being more performant for this case, probably because it doesn't need to keep track of the insertion order like a Set needs. But this is unrelated to garbage collection. – JacquesB Jul 15 '23 at 09:07
  • I see, thanks for clarifying. – Anton Strogonoff Jul 15 '23 at 09:25