Javascript Nested Functions Performance

I have some nested functions like

var freak = function() { var die = function() { ... } die(this); } 

As far as I know, the die function will be created (distributed) every time freak called.

Therefore, if freak gets a lot of time, this means that most of the memory will be wasted (it is assumed that die does not use anything from the freak context, in other words, it works fine even if it is allocated only once and shared between several freak calls - thatโ€™s what I meant in vain).

Do I understand correctly? And is it necessary to completely eliminate nested functions?

+11
javascript garbage-collection memory-management memory-leaks
Nov 05 '13 at 0:13
source share
1 answer

As far as I know, the die function will be created (distributed) every time freak is called.

Yes. It's true. A new functional object is created.

Therefore, if freak gets a lot of time, this means that most of the memory will be wasted [...]

For a very small and usually irrelevant value, "wasted."

JavaScript engines are very efficient these days and can do a lot of tricks / optimizations.

For example, only a functional object (but not the actual function code!) Should be "duplicated" inside.

[...] does this mean that nested functions should be completely eliminated?

No. There is no โ€œloseโ€ problem without an actual test case that shows otherwise. This idiom (nested and anonymous functions) is very common in JavaScript and very well optimized for.

Nested functions provide many benefits, including self-documenting code, small autonomous lexical areas, and other benefits of code isolation / organization.

+21
Nov 05 '13 at 0:22
source share



All Articles