3

Say I instantiate a large object with var and new. After I'm done with it, can I "free" it by setting it to null? Is this something Javascript GCs look for?

  • This may help you: http://stackoverflow.com/a/742666/1249581. – VisioN Jun 02 '12 at 17:43
  • Just try to limit its scope by as much as possible and use `delete` if really needed. – d_inevitable Jun 02 '12 at 17:44
  • @d_inevitable `delete` removes the reference to the object but not the object itself. However, if you remove the reference, GC will know about useless object data faster. – VisioN Jun 02 '12 at 17:45
  • I know. `delete` has merely the effect of setting it to null. Therefore I said, limit the scope as much as possible. – d_inevitable Jun 02 '12 at 17:46
  • @d_inevitable: `delete` is not meant for variables. It only removes properties from objects. –  Jun 02 '12 at 17:47
  • @amnotiam so delete is not officially supported for variables? I've tried this on ff and it works totally fine with variables. – d_inevitable Jun 02 '12 at 17:49
  • @amnotiam hmm you are right, it doesn't work in chrome. – d_inevitable Jun 02 '12 at 17:51
  • @d_inevitable: Yeah, I think there are some browser bugs that sometimes allow it, but they shouldn't. I think the only time it will work is if you set a property on the global object, then use `delete` to remove it. I believe in that case it will successfully remove the global variable as well. Not sure though. –  Jun 02 '12 at 17:54

3 Answers3

5

The garbage collection is interested in objects, that are not referenced by ANY other object. So make sure there are no references left anywhere in your application (Arrays etc.)

Florian Salihovic
  • 3,921
  • 2
  • 19
  • 26
  • https://www.youtube.com/watch?v=RWmzxyMf2cE That's a nice "conference" by Colt McAnlis about Javascript and GC.. It's interesting :) – andrea.rinaldi Sep 29 '14 at 07:09
1

You can break the reference by setting the variable to null, but it doesn't break any other references.

All references need to be broken individually before the object can be GC'd.

So yes, if the only reference to the object that is held by that variable, then setting it to null will free it for eventual GC.

0

as am not i am stated, you'll need to break all references in order for a variable to be eligible for garbage collection. This can be a difficult task if you can't track down that last reference to a specific Object, so use the tools available to you for this task. Personally I use the Chrome's Heap Profiler which you can read about in the chrome docs.

Also, note that only non-primitive types are passed by reference (and therefore only non-primitive types can be GC'd).

bkconrad
  • 2,620
  • 3
  • 20
  • 30