Hari
Hari

Reputation: 31

Is there any memory usage difference between anonymous functions and traditional functions in Javascript? if so, how?

Is there any memory usage difference between anonymous functions and normal functions in Javascript ?

If so, how? Can you explain it?

Upvotes: 3

Views: 164

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382150

If by "normal functions" you mean functions declared as function a(){ at the root level of your script, that is functions attached to the window object, yes there are differences :

  • functions attached to the window object aren't garbaged while anonymous functions can be garbaged as soon as you don't use them anymore.
  • they might slow the access to other variables of the window object (attaching the function at the root level is sometimes qualified of "cluttering global namespace" but the reason to avoid it is mainly to have a cleaner code and avoid name collisions).
  • anonymous functions are closures : they keep a pointer to their enclosing scope, which enables the use of the variables defined in this scope. A side effect is that this scope cannot be garbaged before the function so the function can be heavier than you think and than a "normal function" (you can add an empty scope to enclose the anonymous declaration and prevent this effect if you don't need the variables of the scope but as I don't know if javascript engines can yet optimize away part of the enclosing scope I suggest you don't do it if you don't detect circular references).

But those differences are usually minor, you normally don't have to pay attention to that. In most of your pages your anonymous functions wouldn't be garbaged anyway as you don't remove the event handler (the first root cause of anonymous functions usually).

Globally (premature optimization is the root etc.) I recommend you favor readability as long as you don't have garbaging problems. Javascript engines and their GC change a lot, so your efforts could be useless.

Google has an interesting notice about closure and memory.

Upvotes: 4

Related Questions