JavaScript for loop performance - better inside a function?

Scenario 1:

console.time("loop");
for (var i = 0; i < 1000000; i += 1){
  // Do nothing
}
console.timeEnd("loop");

      

Ran in chrome console, this will return apx 450ms or so.

Scenario 2:

function test() {
  console.time("loop");
  for (var i = 0; i < 1000000; i += 1){
    // Do nothing
  }
  console.timeEnd("loop");
}
test();

      

Run this code is the Chrome console and it is usually & lt; 1ms. I get this example function from the Node interview questions article . I understand that a loop outside a function will have i

permission to the window object, whereas the same loop inside a function scope will i

locally - hence an increase in performance.

My question is, what would be good practice to use your loops in functions whenever possible? ... This performance gain is tempting, but it seems odd to always have loops in functions since I haven't seen code like this.

+3


source to share


1 answer


The answer is that it's good practice to put all of your code in functions. You have to write very little code in the global scope.

While this can lead to performance gains, as you seem to have pointed out, the reason is that it prevents you from placing properties on the window, which can lead to name conflicts with other libraries.

So yes, this is good practice, but not only for this reason.



http://markdalgleish.com/2011/03/self-executing-anonymous-functions/

http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write

What is the purpose of a self-executing function in javascript?

-1


source







All Articles