Is it better to avoid declaring a function too many times for performance in JavaScript?

Viewed 71

I have a function a, which will be executed many times (thousands).

Inside the a function there is a util function, which is ONLY used inside a.

Now I have two options:

First, put the util inside a. It won't "pollute" the outside scope but will be declared once every time a is called.

Second, put the util outside a. It will do the reverse.

Which one is better for performance?

Option 1:

while(xx){
  a();
}
function a(){
  util();
  function util(){
    // will only stay inside a()
    // but will be declared everytime when a is called.
  }
}

Option 2:

while(xx){
  a();
}
function a(){
  util();
}
function util(){
  // only declare once but will be accessed by all other scope outside a().   
}
2 Answers

You should use option 2.

This code sample show that there's a big performance impact when declaring the function multiple times

var start = new Date();
let value = 0;
function add(a,b){
    return a + b;
}
for (var i=0;i<=100000000;i++){
    value += add(2, 5);
}
var end = new Date();
console.log(value);
var timeTaken = end.valueOf() - start.valueOf();
console.log("Took 1 " + timeTaken + "ms");
// Took 198ms

var start = new Date();
let value2 = 0;
for (var i=0;i<=100000000;i++){
    function add(a,b){
        return a + b;
    }
    value2 += add(2, 5);
}
var end = new Date();
console.log(value2);
var timeTaken = end.valueOf() - start.valueOf();
console.log("Took 2 " + timeTaken + "ms");
// Took 1127ms

I'd go with Option 2. Defining a function thousands of times is dismal for performance, and unless you want multiple functions called util for some reason, there's no reason to worry about polluting the global scope. Local variables do tend to cause less lag, but it's not much of a difference.

Related