25

I am looking at the example from http://www.javascriptkit.com/javatutors/oopjs.shtml

var person = new Object()
person.name = "Tim Scarfe"
person.height = "6Ft"

But there is no mention how to "free" it in order to avoid memory leak.

Will the following code free it?

person = null;
  1. How do you free a JavaScript Object using "new Object()?
  2. How do you free a JavaScript Array allocated using "new Array(10)"?
  3. How do you free a JavaScript JSON allocated using "var json = {"width": 480, "height": 640}"?

Thanks in advance for your help.

pion
  • 3,593
  • 6
  • 29
  • 41
  • 2
    It is not JavaScript JSON. It is just object literal notation. It is only JSON if it is a string. See also: http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/#disqus_thread – Felix Kling Dec 23 '10 at 23:26
  • 1
    **Off-topic**: The example code you've gotten from that site isn't very good. 1. `new Object()` => `{}`; 2. It relies on automatic semicolon insertion, which if not the spawn of the devil, is still something you absolutely should not rely on; 3. Okay, this bit's not terrible, but hey, why not teach literal notation? `var person = {name: "Tim Scarfe", height: "6Ft"};` But really it's #2, and #1 to a lesser extent, that make me thing "blech". – T.J. Crowder Dec 23 '10 at 23:57

2 Answers2

60

You don't have to explicitly "free" JavaScript objects. All standard JavaScript hosts/environments use garbage collection based on whether the object can be reached anymore. (There may be niche hosts, such as some for embedded systems, that don't; they'll supply their own means of explicitly releasing things if so.) If the object can't be reached anymore, the memory for it can be reclaimed.

What you can do is ensure that nothing is referencing memory you're not using any more, since memory that is being referenced cannot be released. Nearly all of the time, that happens automatically. For instance:

function foo() {
   var a = [1, 2, 3, 4, 5, 6];

   // Do something
}

The memory allocated to the array a pointed to is eligible to be reclaimed once foo returns, because it's no longer referenced by anything (a having gone out of scope with nothing having an outstanding reference to it).

In contrast:

function foo() {
   var a = [1, 2, 3, 4, 5, 6];

   document.getElementById("foo").addEventListener("click", function() {
       alert("a.length is " + a.length);
   });
}

Now, the memory that a points to cannot be reclaimed, because there's a closure (the event handler function) that has an active reference to it, and there's something keeping the closure in memory (the DOM element).

You might think that only matters in the above, where the closure clearly uses a, but wouldn't matter here where it doesn't:

function foo() {
   var a = [1, 2, 3, 4, 5, 6];

   document.getElementById("foo").addEventListener("click", function() {
       alert("You clicked foo!");
   });
}

But, per specification a is retained even if the closure doesn't use it, the closure still has an indirect reference to it. (More in my [fairly old] blog post Closures Are Not Complicated.) Sometimes JavaScript engines can optimize a away, though early aggressive efforts to do it were rolled back — at least in V8 — because the analysis required to do it impacted performance more than just having the array stay in memory did.

If I know that array isn't going to be used by the closure, I can ensure that the array isn't referenced by assigning a different value to a:

function foo() {
   var a = [1, 2, 3, 4, 5, 6];

   document.getElementById("foo").addEventListener("click", function() {
       alert("You clicked foo!");
   });

   a = undefined; // <===============
}

Now, although a (the variable) still exists, it no longer refers to the array, so the array's memory can be reclaimed.

More in this other answer here on StackOverflow.


Update: I probably should have mentioned delete, although it doesn't apply to the precise code in your question.

If you're used to some other languages, you might think "Ah, delete is the counterpart to new" but in fact the two have absolutely nothing to do with one another.

delete is used to remove properties from objects. It doesn't apply to your code sample for the simple reason that you can't delete vars. But that doesn't mean that it doesn't relate to other code you might run across.

Let's consider two bits of code that seem to do largely the same thing:

var a = {};         // {} is the same as new Object()
a.prop = "foo";     // Now `a` has a property called `prop`, with the value "foo"
a.prop = undefined; // Now `a` has a property called `prop`, with the value `undefined`

vs.

var b = {};         // Another blank object
b.prop = "foo";     // Now `b` has a property called `prop`, with the value "foo"
delete b.prop;      // Now `b` has *NO* property called `prop`, at all

Both of those make the memory that prop was pointing to eligible for garbage collection, but there's a difference: In the first example, we haven't removed the property, but we've set its value to undefined. In the second example, we've completely removed the property from the object. This is not a distinction without a difference:

alert("prop" in a); // "true"
alert("prop" in b); // "false"

But this applies to your question in the sense that deleting a property means any memory that property was pointing to becomes available for reclamation.

So why doesn't delete apply to your code? Because your person is:

var person;

Variables declared with var are properties of an object, but they cannot be deleted. ("They're properties of an object?" I hear you say. Yes. If you have a var at global scope, it becomes a property of the global object [window, in browsers]. If you have a var at function scope, it becomes a property of an invisible — but very real — object called a "variable object" that's used for that call to that function. Either way, though, you can't delete 'em. More about that in the link above about closures.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • +1 For pointing out scope chains and hidden "bindings". I wonder if any JS engine is smart enough to eliminate said cases automatically -- only an "eval" or explicit usage in a nested scope can access the binding (from code) anyway. –  Dec 23 '10 at 23:31
  • Thanks for your help. Will "a = null;" do the same as "a = undefined;"? – pion Dec 23 '10 at 23:37
  • 3
    @pion: *Will "a = null;" do the same as "a = undefined;"*? For the purposes of releasing any other memory `a` was pointing to, yes. I use `undefined` because that's the value properties (and variables) have when they're uninitialized, so I think of `undefined` (rather than `null`) as the "blank" state of properties. But `null` is fine too, and you see it used a lot. :-) – T.J. Crowder Dec 23 '10 at 23:43
  • @pst: *"I wonder if any JS engine is smart enough to eliminate said cases automatically"* If V8 doesn't already do this with code that doesn't have a reference or an `eval` in it (or better, with strict code), I bet it will at some point. Or if it doesn't, you bet there's a very good reason we're not seeing. :-) – T.J. Crowder Dec 23 '10 at 23:47
1

JavaScript does this all for you, but if you want to explicitly free an object or variable, then yes, setting it to null is the closest you can get to doing this.

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • 1
    @Phrogz, you can't delete *variables*, only properties. Try running this (in a script in a page, rather than your Firebug/WebKit console, which lies): `var a='test',b={c:'test'};console.log('a:',a);console.log('delete a:',delete a);console.log('a:', a);console.log('b.c:',b.c);console.log('delete b.c:',delete b.c);console.log('b.c:',b.c);` Then read: http://perfectionkills.com/understanding-delete/ – eyelidlessness Dec 23 '10 at 23:58
  • 1
    Phah. I was sure you couldn't delete variables, then I saw the other answer that suggested it, and I was lazy and only tested it in the console. How embarrassing. :) I'd redact my lies if the timer wasn't up, so instead I'll just kill the comment. Thanks for the vigilance against misinformation. – Phrogz Dec 24 '10 at 01:23