I am asking this question because I and my colleague have a dispute on coding style because he prefers arrows function declaration:
const sum = (a, b) => a + b;
And I prefer old-style standalone function declaration:
function sum(a, b) { return a + b; }
My point is that code in old-style more readable and you can more clearly distinguish function and variable declarations. His point is that code with arrow functions just run faster.
Do you know something about actual performance penalties (in v8) when you use old-style standalone function declaration instead of arrow functions? Are that penalties really exists?
Arrow functions are (mostly) just "syntactic sugar" for conventional function declarations. There is no performance difference.
There are two major benefits of using Arrow functions. One is that it's a shorter syntax and thus requires less code. The main benefit is that it removes the several pain points associated with the this operator.
Function expressions are best for object methods. Arrow functions are best for callbacks or methods like map , reduce , or forEach . Use function declarations for functions you'd call by name (because they're hoisted). Use arrow functions for callbacks (because they tend to be terser).
Unlike regular functions, arrow functions do not have their own this . Arguments objects are not available in arrow functions, but are available in regular functions. Regular functions created using function declarations or expressions are 'constructible' and 'callable'.
V8 developer here. Arrow functions are (mostly) just "syntactic sugar" for conventional function declarations. There is no performance difference.
The following shows that:
function goFat() { for (var i = 0; i < 1000000; i++) { var v = ()=>{}; v(); } } function goTraditional() { for (var i = 0; i < 1000000; i++) { var v = function() {}; v(); } } function race() { var start = performance.now(); goTraditional(); console.log('Traditional elapsed: ' + (performance.now() - start)); start = performance.now(); goFat() console.log('Fat elapsed: ' + (performance.now() - start)); start = performance.now(); goTraditional(); console.log('Traditional elapsed: ' + (performance.now() - start)); start = performance.now(); goFat() console.log('Fat elapsed: ' + (performance.now() - start)); console.log('------'); }
<button onclick="race()">RACE!</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With