In JavaScript, what are the specific reasons why creating functions in a loop can be computationally wasteful?

In JavaScript, what are the specific reasons why creating functions in a loop can be computationally wasteful?

On page 39, โ€œGood Details,โ€ Douglas Crockford states, โ€œAvoid creating functions inside a loop; this can be computationally wasteful.โ€ I cannot understand why creating functions in a loop would be more useless than outside.

+4
source share
2 answers

Because you are creating multiple Function objects instead of reusing only one.

An example of creating an identical function ...

 for (var i = 0; i < 10; i++) { // v--creating identical function in each iteration. (function(j) { var el = document.createElement('a'); el.onclick = function() { alert(j); }; document.body.appendChild(el); })(i); } 

An example of reusing a named function ...

 for (var i = 0; i < 10; i++) { var el = document.createElement('a'); // ----------v---calling a reusable function el.onclick = createHandler(i); document.body.appendChild(el); } function createHandler(j) { return function() { alert(j); }; } 

Two examples have the same result, but the second does not require the overhead of performing two functions during the cycle. Instead, it creates only one handler.

+5
source

Creating a function can use many resources. Since functions are actually objects, the code must actually create a new function object every time, it cannot just create it once, and then just reuse it.

Creating a function inside a loop usually means that you will create many functions instead of creating one function outside the loop.

So, it's just a matter of not doing something resource intensive inside the loop, if you can do it outside the loop instead. When it comes to functions, they can often be created outside the loop without changing the logic of the code.

+2
source

Source: https://habr.com/ru/post/1415374/


All Articles