views:

177

answers:

2

I am currently rethinking the object dispose handling of the qooxdoo JavaScript framework.
Have a look at the following diagram (A is currently in scope):

diagram

Let's say we want to delete B. Generally, we cut all reference between all objects. This means we cut connection 1 to 5 in the example. Is this really necessary?
As far as I have read hear 1, browsers use the mark-and-sweep algorithm. In that case, we just need to cut reference 1 (connection to the scope) and 5 (connection to the DOM) which could be much faster.
But can I be sure that all browsers use the mark-and-sweep algorithm or something similar?

1 http://stackoverflow.com/questions/864516/what-is-javascript-garbage-collection

+2  A: 

For any decent garbage collector (not only mark-and-sweep), cutting connection 1 would be enough to release B (and C and D and the window). Allocation based on reference counting would fail to release B and D due to their cyclic references (B references D and D references B) but reference counting is not really garbage collection.

I think it is safe to assume that all browsers use a decent garbage collector (well, with browsers, nothing is ever really safe, but a JavaScript implementation not using a proper garbage collector is improbable nonetheless).

Thomas Pornin
Reference counting is not sufficient to implement garbage collection, but it can still be part of a decent GC. When the count hits 0, you positively know that you can collect the object. This shortcut can allow you to GC many objects without an expensive mark-and-sweep step. In addition, when the time does arrive to do a mark-and-sweep, there's less garbage left to clean up.
MSalters
Reference counting is expensive, due to the updates to the counts (especially with regards to cache). Asymptotically, even without cycles, mark-and-sweep is less expensive than reference counting. Reference counting, however, better interacts with virtual memory in some situations, which is why Perl uses it (Perl believes in dynamic bindings by names rather than pointers, and thus creates very few "true cycles"; however, Perl _also_ has a mark-and-sweep GC).
Thomas Pornin
+2  A: 

The thing is that in an ideal world, you basically just need to disconnect DOM nodes and native event listeners. Problem is though, that the original system in qooxdoo was designed around buggy browsers like IE6. We saw massively reduced memory usage when we delete as much as possible on our own. In todays world I would however redesign it in a way that it's OK in IE6, but not optimized for its problems.

There is also a difference of a complete shutdown of the whole application (dispose all) and just to dispose a single fraction of an application. In the last scenario you need to act quite carefully to not dispose stuff which is still needed.

Sebastian Werner