Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript nested function performance

I have some nested functions such as

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

As far as I have learned, the die function will get created (allocated) each time freak is called.

So if freak gets called a lot of time, that means a lot of memory will be wasted (assuming die is not using anything from freak's context; in other words, it works fine even if it was allocated only once and shared between multiple calls of freak – this is what I meant with wasted).

Is my understanding correct? And does that mean nested functions should be avoided entirely?

like image 903
Khanh Nguyen Avatar asked Nov 05 '13 00:11

Khanh Nguyen


People also ask

Can functions be nested in JavaScript?

JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to).

Should I define a function inside a function?

If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.

What is nesting in JavaScript?

Nesting is when you write something inside of something else. You can have a function inside of another function: function x () { function y() { // something; } } You can have an if condition inside of another if condition: if (daylight) { if (before 12) { //It's morning; } else { // it's afternoon; } }


1 Answers

As far as I have learned, the die function will get created (allocated) each time freak is called.

Yes. This is true. A new function-object is created.

So if freak gets called a lot of time, that means a lot of memory will be wasted [...]

For some very small and normally inconsequential value of "wasted".

JavaScript engines are very efficient these days and can perform a wide variety of tricks/optimizations.

For instance, only the function-object (but not the actual function code!) needs to be "duplicated" internally.

[...] does that mean nested functions should be avoided entirely?

No. There is no "wasting" problem without an actual test-case that shows otherwise. This idiom (of nested and anonymous functions) is very common in JavaScript and very well-optimized for.

Nested functions provide many benefits including self-documenting code, smaller self-contained lexical scopes, and other code isolation/organization advantages.

like image 125
user2864740 Avatar answered Sep 21 '22 16:09

user2864740