Null and delete () for garbage collection

advertisements

Anyhow, If I were to write something like:

var h = 5;
delete h;

...I'd be eliminating the reference, but not the memory.
Now, if I set the variable to null, would that replace the memory with the null object?

var h = 5;
h = null;

If so, wouldn't it be better to not only delete() the reference, but also replace the memory with a null object, for better memory optimization?

var h = 5;
h = null;
delete h;

If I want to create a bucket-load of dynamic objects in a long and complex script, what's the best way to get rid of, or otherwise induce the garbage collector to eliminate, objects? Because in addition to just eliminating references, I had read that you could hint the collector to free memory if it was occupied by null...


There's no destroy. You're probably thinking about delete, but delete can't be used to delete variables, only properties. (Although currently browsers let you get away with it, with varying results.) You can delete global variables by removing them from window, but not locals.

Anyway you don't need to think about this sort of stuff in JavaScript. Set a variable to null and if there are no more variables pointing to the same object, it'll get garbage-collected at some point in the near future. The amount of space taken up by the record of the variable pointing to null is tiny and not worth worrying about. Unless you are making a deliberate closure it'll fall out of scope anyway when the local function exits, becoming eligable for GC.

I had read that you could hint the collector to free memory if it was occupied by null...

Nope. You're just removing the references, the GC will pick up the now orphaned objects and free the memory at its own leisure. You don't get any say in the matter.