1

A closure:

function test() {
  var count = 0;

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

As we all know, the count won't release after test() be called, and now if the closure is useless to me, how could I release memory of it?

CoderLim
  • 1,222
  • 3
  • 11
  • 23
  • what do you want to release if there is only one variable which you intend to use in future because you returned it in a function? – pwolaq Sep 20 '16 at 05:48
  • What is purpose of returning anonymous function where no value is returned from anonymous function? Are you trying to `return` `count` from anonymous function returned by `test()` call? – guest271314 Sep 20 '16 at 05:51
  • 1
    refer this link may be useful for you : http://stackoverflow.com/questions/7248122/how-do-you-clear-memory-in-javascript – Sunil Kumar Sep 20 '16 at 05:52
  • I would expect the closure to be garbage collected at some point after you release the last reference to the returned function. – nnnnnn Sep 20 '16 at 05:59

2 Answers2

6

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

slebetman
  • 109,858
  • 19
  • 140
  • 171
0

closures is a massive source of memory leaks in JavaScript.

   function foo() {
    var count = 0;
    function do() {
     return count++;
    }
    return {
     do: do}
   } 

Here foo() return the do function expression and do() have closure over th e count variable. We don't know when the returned do() expression will be called. So the garbage collector can't understand when to release the memory. So we need to manually release it after its usage.

Rony Cherian
  • 114
  • 3