Zoltán Tamási Zoltán Tamási - 10 days ago 6
Javascript Question

Are there any potential memory leaks when using deferreds?

I get a

jQuery.Deferred
somewhere in my code, and I add several callbacks to it which are member methods of short-lived objects. I was wondering if there are any kind of memory leak potential in this situation, similarly like in .NET event handlers.

I was checking the code of
jQuery
, but haven't seen any part where callbacks are cleared. I didn't even find where the lifecycle of a deferred object should end.

Could anyone please shed some light on this topic?

EDIT

As I'm thinking about it, it narrows down to this question. In JavaScript, will holding a reference to a member function of an object (not prototype) deny the object from being GC-d? Because jQuery seems to hold these function references in the callbacks of the deferred object.

Answer

I haven't seen any part where callbacks are cleared.

The callbacks are cleared when the promise is settled (fulfilled or rejected).

I didn't even find where the lifecycle of a deferred object should end.

The lifecycle of a promise ends when nothing holds a reference to it any more.

There are generally two things that hold a reference to it: the resolver (e.g. timeout, ajax request etc) that eventually will settle the promise, and entities that store the promise because they want to use it (i.e. its result) later. The promise object in turn holds a reference to all the callbacks (until settled), and to the result value (since settled).

A leak can occur if the promise is never resolved, has callbacks attached to it, and is prevented from being garbage-collected by some references. That's very rare though.

In JavaScript, will holding a reference to a member function of an object (not prototype) deny the object from being GC-d?

No, in general not. There are no "members" in javascript, just plain standalone functions.

Though of course the function, when being a closure, could hold a reference to the object, and would keep it from being collected.