Nested functions and performance in javascript?

Some of the employees say that nesting functions are bad for performance, and I wanted to ask about it.

Suppose I have a function:

function calculateStuff() { function helper() { // helper does things } // calculateStuff does things helper(); } 

helper is a private function that is used only inside calculateStuff. This is why I wanted to encapsulate this inside calculateStuff.

Is it really worse quality than doing:

 function helper() { } function calculateStuff() { helper(); } 

Please note that in the second case, I provide an assistant to my area.

+8
performance javascript nested-function
source share
2 answers

With your first code, every time you call calculateStuff a new copy of helper will be created.

With your second code, all calls will have the same helper , but it will pollute the outside area.

If you want to reuse helper without polluting the outside, you can use IIFE:

 var calculateStuff = (function () { function helper() { // helper does things } return function() { // calculateStuff does things helper(); } })(); 
+5
source share

In theory, there is a potential performance impact because you need to create a new closing context for the helper every time calcStuff is called (because it can refer to variables from the scope).

I am sure that the JIT compiler in most JavaScript engines should be able to say that you are not actually accessing any variables from the parent context and just skip the binding of all these values. Perhaps I’m missing an edge where this is not possible at all, but it seems like it's quite complicated.

In any case, we are talking about nanoseconds of overhead for iteration, so if your code does not execute a lot, you will never notice the time difference. If in doubt, profile it and check ...


I decided to follow my own advice and describe it on jsperf using Safari 9. I used the do-nothing functions as provided in the original question to highlight the overhead just for calling the nested function:

Nested functions: 136 million calls per second

Flat features: 1,035,000,000 calories per second

Oriol IIFE version : 220 million calla per second

Clearly, flat functions are much faster than any of the alternative versions. However, think about the magnitude of these numbers - even the β€œslow” version adds only 0.007 microseconds to the run time. If you perform any calculations or manipulations with the DOM in this function, this will absolutely eclipse the overhead of the nested function.

+8
source share

All Articles