Best way to deallocate an array of array in javascript

后端 未结 3 1655
北恋
北恋 2020-12-18 05:26

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         


        
相关标签:
3条回答
  • 2020-12-18 06:11

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

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

    You can also combine 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 讨论(0)
  • 2020-12-18 06:18
    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 complicated if any of those array elements contain references to DOM nodes.

    0 讨论(0)
  • 2020-12-18 06:27

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

    .. or use a namespace object

    var namespace = {};
    namespace.foo = [];
    delete namespace.foo;
    
    0 讨论(0)
提交回复
热议问题