32

var Obj = function(){}; var X = new Obj();

will X = null properly clear memory?

Also would this be equivalent?

var Obj = function(){}; 
var X   = {}; 
X.obj   = new Obj();
delete(X.obj);

EDIT It would seem that although deleting X.obj would NOT immediately clear memory, it would help the garbage collection. If I don't delete X.obj, there would still be a pointer to an object and so the GC may not clean it up.

Although I'm picking @delnan's answer, if you're reading this you should def also catch Benubird's article.

I also notice I accidentally wrote delete(X) originally instead of delete(X.obj) - sorry.

Dave Stein
  • 8,653
  • 13
  • 56
  • 104
  • You should explain why you are interested in "cleared memory". Is it to reduce RAM usage? Or for security? Or something other reason? – Ned Batchelder Aug 30 '11 at 18:57
  • To reduce RAM usage / make sure the GC hits it – Dave Stein Aug 30 '11 at 18:57
  • I like this question. Unfortunately as with most memory managed environments the best approach is to let the GC do it's job. Oh, and watch holding on to references. – Kris Krause Aug 30 '11 at 19:01

6 Answers6

25

The short answer is that you don't. delete simply removes a reference (and not in the way you try to use it, see the above link - delete is one of those language features few people actually understand), nothing more. The implementation clears memory for you, but it's not your business when (and even if, strictly speaking - this is why one shouldn't rely on finalizers in GC'd languages that offer them) it does. Note though:

  • Only objects that can be proven to be unreachable (i.e. no way to access it) to all code can be removed. What keeps references to whom is usually fairly obvious, as least conceptually. You just need to watch out when dealing with lots of closures, as they may capture more variables than you think. Also note that circular references are cleaned up properly.
  • There's a bug in old (but sadly still used) IE versions involving garbage collection of JS event handlers and DOM elements. Google (perhaps even SO) should have better material on my memory.

On the plus side, that means you won't get dangling pointer bugs or (save of course the aforementioned pitfalls) memory leaks.

  • So in the above code example, wouldn't the new Obj() be removed from memory via garbage collection, since nothing points to it anymore? – Dave Stein Aug 30 '11 at 18:49
  • After the first snippet, the created object is no longer referenced and can thus be collected. The second misuses `delete` (see Benubird's link) and the outcome depends on if the implementation lets you delete variables, but if it does, there's no reference remaining. Otherwise, the objects can become garbage collected as soon as `X` falls out of scope. Either way, the memory is freed *at some point in time* after (NOT immediately, unless by incredible chance) after the object isn't reachable anymore. –  Aug 30 '11 at 18:52
  • I just noticed I made a typo in my snippet. I mean to put delete(X.obj). So should I do delete( X.obj ) or X.obj = null to speed up GC? – Dave Stein Aug 30 '11 at 19:02
  • Neither, unless you've proven there's a problem with a reference being kept around too long (as Kris Kause stated, the GC works very well on itsown). And in which case either works equally well - you get rid of it, and that's all that matters. Handling both `null` and `undefined` requires more code though, so you may want to stick to one. –  Aug 30 '11 at 19:04
  • Actually I never find myself in the situation I need to set global vars to null... just object properties ( like if I have a collection of objects and want to remove one of the pointers). So actually I can stick with using delete( X.obj ). Although it's good that this clarified what the two cases do. – Dave Stein Aug 30 '11 at 19:11
  • @delnan, When you say " the memory is freed at some point in time after (NOT immediately, unless by incredible chance)" , you mean Garbage Collector is not run when we 'delete' some object or make it to 'null' and instead it runs periodically depending on some algorithm ? Or does GC run continuously and wait for objects to be dereferenced? – Vishal-L Apr 24 '18 at 11:06
13

No, that will not clear memory.

Read this:

http://perfectionkills.com/understanding-delete/

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Benubird
  • 18,551
  • 27
  • 90
  • 141
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Mistalis Mar 07 '17 at 10:04
  • @Mistalis how about also including a link to the internet archive of it for future reference? – Benubird Mar 23 '17 at 12:13
  • 1
    @Benubird Please check [What is a link-only answer?](https://meta.stackoverflow.com/questions/288055/please-define-link-only-answer) – Mistalis Mar 23 '17 at 12:21
4

No - Javascript runs GC when it feels like it.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
4

The Delete method only deletes the reference - not the object. Any other references would be left out in the open waiting for the garbage collector.

JavaScript has its own GC, and it will run around and clean things up when nothing refers to them anymore.

I still think it's a good practice to null objects. Deleteing an object also helps the GC because it will see something dangling, and say "I'm going to eat you because you're all alone (and now some cynical laugh)".

You should look at Deleting Objects in JavaScript

Even though there's a GC, you still want to ensure your script is optimized for performance as peoples computers, browsers, and fricken toolbars (and the number of them), will vary.

Community
  • 1
  • 1
Ryan Ternier
  • 8,714
  • 4
  • 46
  • 69
2

Generally speaking, memory management in Javascript is user-agent-specific. The basics of the garbage collector are through reference-counting. So, by setting a reference to null (using the delete keyword or by explicit assignment), you can assure yourself that a reference will be cleaned up, IF the object does not have any references that will live outside of its creation scope. That being the case, the GC will have already cleaned up any objects or variables whose scope has ended without your explicitly setting it to null.

There are some things to take care of, though - circular references are easy to create in JS, especially between a DOM element and an object. Care must be taken to clear (or not create in the first place) references to and/or from DOM elements within objects. If you do create a to/from reference related to DOM, be sure to explicitly clean them up by setting the references to null - both on your object and on the DOM element. Simply setting a parent object to null is not sufficient if there are child objects with references to/from DOM or localStorage because those references will live on, and if there was any reference from the child to the parent, then the parent will live on in memory because of that reference.

Web pages can actually leak trash in your memory this way - after you navigate away, the circular references keep objects and DOM elements in memory until you've restarted the browser!

An article on the subject: http://docstore.mik.ua/orelly/webprog/jscript/ch11_03.htm, and another detailed look: http://blogs.msdn.com/b/ericlippert/archive/2003/09/17/53038.aspx

Yoon5oo
  • 496
  • 5
  • 11
Chris Baker
  • 49,926
  • 12
  • 96
  • 115
1

JavaScript memory is generally handled similarly to Java - I mean there is (or there should be) a garbage collector which would delete the object if there is no references to it. So yes, simply "nullifying " the reference is the only way you should "handle" freeing memory, and the real freeing is the JS host part.

Roman Pietrzak
  • 635
  • 3
  • 15