How does Object.observe/unobserve interact with garbage collection?
Asked Answered
G

1

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?

Granada answered 14/8, 2014 at 17:46 Comment(0)
D
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.

Dodeca answered 15/8, 2014 at 18:42 Comment(2)
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?Granada
@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.Dodeca

© 2022 - 2024 — McMap. All rights reserved.