how to release closure's memory in javascript?

前端 未结 2 1592
名媛妹妹
名媛妹妹 2021-01-16 04:08

A closure:

function test() {
  var count = 0;

  return function() {
    count++;
  };
}

As we all know, the count won\'t rele

2条回答
  •  野的像风
    2021-01-16 04:10

    All objects in javascript is garbage collected, regardless of weather they're involved in a closure or not. In your code above, if you do:

    var x = test();
    

    then of course the memory for count cannot be released because it may be used later by x. However if you do:

    var x = test();
    x = "";
    

    the memory for count will be garbage collected sooner or later.

    Also, if you do:

    function foo () {
        var x = test();
        x();
    }
    
    foo();
    

    the memory for count would also be garbage collected because x goes out of scope when foo() ends.

    The best way to ensure you don't have memory leaks in javascript is to avoid global variables.

    Note: The garbage collector in old versions of IE used a simple reference count which means that circular data structures are not garbage collected. This was fixed in either IE6 or IE7 and was never a problem in other javascript engines which normally use a mark-and-sweep garbage collector

提交回复
热议问题