Chrome/V8 does not garbage collect a circular reference? Chrome/V8 does not garbage collect a circular reference? google-chrome google-chrome

Chrome/V8 does not garbage collect a circular reference?


To be completely honest we would need a quick look at some test code where you replicated this but I have a general idea of what you are experiencing. If I am wrong and you can provide some test code that proves this, please let me know.

As you seem to already know, to 'clean up', Javascript wants no more references to the item looking to be freed.

A simple example:

// Currently not eligible for garbagevar myObj = {    data : 'test'};// Reference data inside myObj// A unique identifier to myObj.data now exists var myData = myObj.data;// WhoopsmyObj = 'something else';// Because myData exists, so does data and can not be freed either, understandable// This sounds simple and logical but most do not understand what is happening in the engine// A relationship has been born between 'myData' and 'data' and as long as it exists, it is not eligible for garbage and remains in memoryconsole.log( myData );

Your code is probably more complicated than this but this might help explain how, somewhere, the garbage can not be collected as the scope chain can be followed to a reference.

Consider the following

function oops(text){    function doStuff(){        return text.toLowerCase();    }    return doStuff();}// 'doStuff' stays alive thanks to 'test' below.var test = oops('closure');

the function doStuff will not be garbage collected because it is being referenced by test.

// You can see where this is headed. We have 2 references to the same 'doStuff' function object with separate unique identifiers now below.var test2 = oops('closures...');// This is now another unique identifier to 'doStuff'var test3 = test2;// doStuff survives yet stilltest = 0;test2 = 0;// Now we let the function object of 'doStuff' be freed because there is no longer any references to ittest3 = 0;

This is essentially a memory leak we created. Each time you call oops you are creating a function object doStuff with a unique identifier.

A way to avoid this could be

function doStuff( text ){    return text.toLowerCase();}function oops( text ){    return doStuff();}var test = oops( 'closure' );

Now we have no memory leaks. doStuff is being invoked and not created.

A closer look at your code and you will find you are probably doing this somewhere.

If you are messing with elements and I think you might be, IBM has a good article about circular references you may want to take a look at.


It's late and some of this was untested, but the theory is still there so if I misspelled something etc, let me know and I can take a look tomorrow for future visitors to this page.