views:

497

answers:

2

Should I free the allocated memory by myself, or is there a kind of garbage collector?

Is it ok to use th following code in javascript?


function fillArray()
{
  var c = new Array;
  c.push(3);
  c.push(2);
  return c;
}

var arr = fillArray();
var d = arr.pop()

thanks

+6  A: 

Quoted from the Apple JavsScript Coding Guidelines:

Use delete statements. Whenever you create an object using a new statement, pair it with a delete statement. This ensures that all of the memory associated with the object, including its property name, is available for garbage collection. The delete statement is discussed more in “Freeing Objects.”

This would suggest that you use a delete command to then allow the garbage collector to free the memory allocated for your Array when you're finished using it. The point that the delete statement only removes a reference is worth noting in that it differs from the behaviour in C/C++, where there is no garbage collection and delete immediately frees up the memory.

Noldorin
Just keep in mind that the "delete" operator doesn't actually 'delete' an object—it just removes a reference to the object so that JavaScript's Garbage Collector can easily see that the object is not being used anymore. For more information, see the following question: http://stackoverflow.com/questions/742623/deleting-objects-in-javascript.
Steve Harrison
@Steve: Good point - I'll edit the post.
Noldorin
+3  A: 

The variables arr and d will exist as global variables and will exist until you do something with them i.e. use delete. You might want to contain their scope to a function and do what you need to do with them inside that function.

Russ Cam