Will this javascript cause memory leak?
function outer(){
var a, b, c;
function inner1(){
...
}
function inner2(){
...
}
inner1();
inner2();
...
}
I want to keep the global namespace clean so I wrote above code. Inner functions are only used by code in开发者_StackOverflow社区side Outer. But after that I begin to thought if this will cause any memory problem. I'm not sure whether the inner functions are created beforehand or created each time the outer() is called? And will them cause memory leak?
Could someone help explain what will happen when outer() is called and when it returns? And please refer me if there are any good books or articles about javascript memory management. I always get confused by such problems. Thanks.
Not sure about first part but there is a similar question about the second part:
Do you know what may cause memory leaks in JavaScript?
How do I track and debug JavaScript memory leaks in Firefox?
The main problem that causes memory leaks in browsers with JavaScript is the fact, that the DOM and JS have two independet garbage collectors. If you begin to have references to DOM elements in your closure function and then again backreference to something inside the function you will face problems. Your structure is not leaking, but you want to do some more stuff and that maybe leaking.
In answer to your question about the creation of the inner functions: I believe your inner functions are created/defined every time you run outer()
, and most JS interpreters should garbage-collect them after outer()
runs, along with all the other variables in the function scope - unless outer()
"exports" these inner functions outside of its own scope, e.g. assigning them as event handlers or including them in a return statement for later use.
Unless you put some other code inside - you should not worry about leaks in such simple closures. Modern javascript engines handle those very well.
精彩评论