最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Best way to deallocate an array of array in javascript - Stack Overflow

programmeradmin1浏览0评论

What is the best way to deallocate an array of array in javascript to make sure no memory leaks will happen?

var foo = new Array();
foo[0] = new Array();
foo[0][0] = 'bar0';
foo[0][1] = 'bar1';
foo[1] = new Array();
...
  1. delete(foo)?
  2. iterate through foo, delete(foo[index]) and delete(foo)?
  3. 1 and 2 give me the same result?
  4. none?

What is the best way to deallocate an array of array in javascript to make sure no memory leaks will happen?

var foo = new Array();
foo[0] = new Array();
foo[0][0] = 'bar0';
foo[0][1] = 'bar1';
foo[1] = new Array();
...
  1. delete(foo)?
  2. iterate through foo, delete(foo[index]) and delete(foo)?
  3. 1 and 2 give me the same result?
  4. none?
Share Improve this question edited Jun 8, 2010 at 17:18 BalusC 1.1m376 gold badges3.6k silver badges3.6k bronze badges asked Jun 8, 2010 at 17:13 andre.diasandre.dias 811 silver badge3 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9
foo = null;

should be enough for the garbage collector to get rid of the array, including all its child arrays (assuming nothing else has a reference to them). Note that it will only get rid of it when it wants to, not immediately, so don't be surprised if the browser's memory consumption doesn't drop straight away: that isn't a leak.

It potentially gets more plicated if any of those array elements contain references to DOM nodes.

you can't delete variable, set it null foo = null;

.. or use a namespace object

var namespace = {};
namespace.foo = [];
delete namespace.foo;

I think Array.splice also might do the trick for you. Its an alternative to using delete on each index.

Ref: https://developer.mozilla/En/Core_JavaScript_1.5_Reference/Objects/Array/Splice

You can also bine it with Array.forEach like this:

foo.forEach(function(element,ind,arr){
 arr.splice(ind,1);  //emptying the array
});
foo = null; //remove ref to empty array

If you just use the forEach part, you will empty the foo array. I think internally the splice method removes a reference so you will be good removing elements this way.The last line then removes the reference to the empty array that is left.

Not very sure on this but worth some research.

发布评论

评论列表(0)

  1. 暂无评论