bububut
bububut

Reputation: 95

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 inside 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.

Upvotes: 4

Views: 331

Answers (4)

yunzen
yunzen

Reputation: 33439

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.

Upvotes: 1

nrabinowitz
nrabinowitz

Reputation: 55688

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.

Upvotes: 0

Daniel Fath
Daniel Fath

Reputation: 18069

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?

Upvotes: 2

c69
c69

Reputation: 21497

Unless you put some other code inside - you should not worry about leaks in such simple closures. Modern javascript engines handle those very well.

Upvotes: 0

Related Questions