views:

80

answers:

2

Hi all, is there a way to know when an object will be disposed by GC?

My object (call it A) write some variables in a global array-object, so when the object will be garbaged its own variable will stay in the global array-object, taking up memory.

ps. i have numerous objects A and i prefer to not call "manually" a method to free my global array-object.

This is my situation:

var global_array=[];

function A(x){
    global_array.push({who:"A", what:x, id:A.instance++});
    this.x=x;
}
A.instance=0;
A.prototype.useIt=function(){
    return this.x*2;
}

//will be created an A object and will be garbaged after use by GC
function test(){
    var a=new A(10);
    var y=a.useIt();
}

test();
//i will never use <a> object again, but global_array hold {who:"A", what:10, id:0)}

DO NOT WANT

A.prototype.dispose=function(){
    // free global_array at the correct index
}

Thanks.

+2  A: 

I'm not exactly sure what the question is, but I can tell you this:

  1. You can't tell exactly when an object will be garbage collected

  2. An object cannot be garbage collected until all references to it have been deleted, so keeping a reference to an object in an array stored in a global variable will ensure that it isn't garbage collected until the page unloads.

Tim Down
A: 

And what about clearing it from globla_array at the end of test method? As you are saying it won't be used anymore, it will be safe to clear that info.

EDIT: In response to your comment (as I think I can't get it clearly stated), let's asume you can get to know when object A is gc:

function objectGetGC(sender)
{
    // You still have to implement here how to clear global_array from object data
    // javascript won't know how to do it on its own.
}

If global_array holds a reference to object A, instead of only data, it won't be gc...

Hope that now is a bit clear what I mean.

MaLKaV_eS
yes but i prefer to not free it manually...
blow
But, even if you get to know when some object has been garbage collected... You'll still have to clear manually your array. As Tim has pointed out, if there's a reference in your global_array to object A, it will not be garbage collected. And that reference will be the only way javascript will clear reference automatically from global_array.
MaLKaV_eS