4

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

On page 39 of JavaScript the Good Parts, Douglas Crockford states, "Avoid creating functions within a loop. It can be computationally wasteful". I can't seem to figure out why creating functions within a loop would be anymore wasteful than outside.

okonomichiyaki
  • 8,355
  • 39
  • 51
TheBrent
  • 2,853
  • 3
  • 16
  • 14
  • possible duplicate of [JSlint error 'Don't make functions within a loop.' leads to question about Javascript itself](http://stackoverflow.com/questions/3927054/jslint-error-dont-make-functions-within-a-loop-leads-to-question-about-javas) ? (That discussion is indeed interesting anyway) – Fabrizio Calderan May 31 '12 at 13:40
  • In javascript, functions are first-class objects, so it always creates a new function object when you use a function expression. If you use function declaration (more comparable to other languages), that is hoisted and not even ran in the loop at all. – Esailija May 31 '12 at 13:43
  • @Esailija: Except that you shouldn't place a function declaration inside the statement block of the loop (even if some implementations will still hoist it). It needs to go before or after the loop. –  May 31 '12 at 13:51
  • 1
    @amnotiam true, just mentioning it for "thoroughness" :P – Esailija May 31 '12 at 13:51

2 Answers2

5

Because you're creating several Function objects instead of reusing just one.

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);
}

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); };
}

The two examples have the same outcome, but the second doesn't require the overhead of making two functions during the loop. Instead it creates just the one handler.

2

Creating a function can use a lot of resources. As functions are in fact objects, the code has to actually create a new function object each time, it can't just create it once and then just reuse it.

Creating a function inside a loop usually means that you will be creating a lot of functions instead of just creating a single function outside the loop.

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

Guffa
  • 687,336
  • 108
  • 737
  • 1,005