7

Does having an active Object.observe on an object prevent it from being garbage collected? Do you need to first call Object.unobserve to allow it to be garbage collected? Or does GCing an object remove all its active observers?

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
alexp
  • 3,229
  • 2
  • 25
  • 34

1 Answers1

7

Observing an object does not keep it alive. Once the object dies, its observers simply won't receive any more events. At least that's true in V8's implementation, which is the only one so far. It's probably safe to assume that it will hold for other implementations as well, should this feature become standard some day.

However, observation keeps its active observers alive, plus some internal, heap-allocated data structures associated with each observer function. In fact, this additional data will only die when the function itself has also died, even if it has long ceased to observe anything.

Andreas Rossberg
  • 31,309
  • 3
  • 55
  • 70
  • I see. So is it safe to say you have to say you have to do your own bookkeeping for all the observers you create, and separately call Object.unobserve before you remove the reference to the observed object? – alexp Aug 15 '14 at 20:14
  • 2
    @alexp, that shouldn't be necessary. A function observing only dead objects is no longer "active" in the sense I meant above. In fact, trying to manually manage life time is so easy to get wrong that there is a good chance that the extra bookkeeping data it'll introduce keeps stuff alive _longer_. – Andreas Rossberg Aug 16 '14 at 07:59