1

Let say I got this:

for(var i = 0 ; i < 100000 ; i++)
{
    // I know, this is not recommended to do it that way...
    // Used it because it is the easiest way to create 
    // different functions to explain the question. 

    a = [ new Function('return ' + i) ];    
}
a = 0;

Are the functions created simply deleted? Or they still exist but can not longer be accessed? Can I have a memory issue with this code? (Not talking about performance)

Note: I'm not actually "overwriting" functions directly: I'm overwriting the object that contains the function.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
RainingChain
  • 7,397
  • 10
  • 36
  • 68

2 Answers2

7

As long as nothing references the said objects (that includes functions), then they will be garbage collected.

For instance, the mark-and-sweep algorithm walks through the objects to check for potential "garbage". Once an object is "unreachable" (cannot be accessed by any of the code), it is marked for garbage collection.

Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 2
    +1. Note that old versions of IE (I think 8 and lower) may leak some functions even if there is no references left (i.e. see http://stackoverflow.com/questions/11186750/memory-leak-risk-in-javascript-closures). Hopefully you don't need to worry about old versions and even if you do it is somewhat easy to observe (not necessary to easy fix) – Alexei Levenkov Dec 31 '13 at 02:22
3

In your example, you created an anonymous function, which means it is defined with the function operator. In other words, it is like as an object, just the same as an expression like this 1+1, and it is created at runtime. Because it is an anonymous function, if you stop referencing it, it is no longer defined, thus the browser's garbage collection deletes it. For more information, I would recommend looking at this post.

Community
  • 1
  • 1
hkk
  • 2,069
  • 1
  • 23
  • 48