Skip to content Skip to sidebar Skip to footer

Is An Arrow Function More Performant Than A Similar Regular (anonymous) Function?

According to MDN: An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, s

Solution 1:

How is an arrow function more performant than a similar regular (anonymous) function?

It isn't. Both are function type, and the performance difference is negligible.

Solution 2:

It's more performant if you are in a situation where you need to reference this and the arrow function exposes the this from the outer scope, so that you don't need to do the let that = this; shenanigan:

let obj = {
  count: 1,

  doSomething: function() {
    this.count++
  },

  faster: function() {
    setTimeout(() => {
      this.doSomething();
    }, 1000);
  },

  slower: function() {
    let that = this;
    setTimeout(function() {
      that.doSomething();
    }, 1000);
  },
};

Solution 3:

My presumption is unfounded. Based on the following timings, creating an arrow function is not more performant than creating a regular anonymous function.

Regular Anonymous Function

let f;
for (let I = 0; I < 10; ++I) {
    console.time();
    for (let i = 0; i < 1000000000; ++i) f = function (x) {return x;};
    console.timeEnd();
}
[Debug] default: 14665.279ms
[Debug] default: 14716.809ms
[Debug] default: 14640.227ms
[Debug] default: 14786.576ms
[Debug] default: 14748.089ms
[Debug] default: 14785.006ms
[Debug] default: 14795.267ms
[Debug] default: 14861.353ms
[Debug] default: 14878.316ms
[Debug] default: 14955.095ms

mean = 14783.202 ± 30.705 ms

Arrow Function

let f;
for (let I = 0; I < 10; ++I) {
    console.time();
    for (let i = 0; i < 1000000000; ++i) f = (x) => {return x;};
    console.timeEnd();
}
[Debug] default: 14683.146ms
[Debug] default: 14772.154ms
[Debug] default: 14756.878ms
[Debug] default: 14667.755ms
[Debug] default: 14729.087ms
[Debug] default: 14770.861ms
[Debug] default: 14808.871ms
[Debug] default: 14865.292ms
[Debug] default: 14901.789ms
[Debug] default: 14928.623ms

mean = 14788.446 ± 27.802 ms

Post a Comment for "Is An Arrow Function More Performant Than A Similar Regular (anonymous) Function?"