Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there performance gains in using ES6 Arrow Functions?

The new arrow functions in ES6, are like one-liner functions which make code more clean and concise, and also allow you to keep the scope of the caller inside the function, so that you don’t need to do things like var _this = this;, or use the bind function etc.

Are there any significant performance gains in using ES6 arrow functions over plain javascript functions?

like image 339
grizzthedj Avatar asked Mar 13 '17 20:03

grizzthedj


People also ask

When you should not use arrow functions in ES6?

An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.

Are arrow functions faster JS?

Arrow functions are (mostly) just “syntactic sugar” for conventional function declarations. There is no performance difference.

Is it better to use arrow functions?

Arrow functions are best for callbacks or methods like map, reduce, or forEach. You can read more about scopes on MDN. On a fundamental level, arrow functions are simply incapable of binding a value of this different from the value of this in their scope.

What is the difference between a normal function and an ES6 arrow function?

Since regular functions are constructible, they can be called using the new keyword. However, the arrow functions are only callable and not constructible, i.e arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword.


2 Answers

Keep in mind there can’t be an universal answer to this question, as always with all of which is implementation dependant. So the answer may be X now or with some browsers, and may be Y in the future or with other browsers.

These provisions said, here are some data: http://incaseofstairs.com/six-speed. For now and with major browsers, the answer is rather No and there might even be performance penalties (under the above provisions).

like image 176
Hibou57 Avatar answered Oct 05 '22 23:10

Hibou57


It is the opposite: "Arrow functions are slower".

From the theoretical perspective (not specific to JavaScript), lambdas (arrow functions) are anonymous, and so they are usually calculated during runtime on the heap.

This means the compilers may not be able to "inline" the calls to these lambdas. This degrades the performance of lambdas compared to normal free pure functions that have a much higher chance of inlining.

Being on the heap also puts the garbage collector under pressure. See this comment from the author of TypeScript that explains why arrow functions are slower.

An example benchmark:

An arrow method is 10% and 60% slower than a class method and a free function respectively

https://jsbench.me/g4kjcq9j3s/1

like image 31
Amin Avatar answered Oct 05 '22 23:10

Amin