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?
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>
I think arrow functions in class properties might cause some performance issue. Here is an example :
class Car {
setColor = (color) => { this.color = color; }
constructor() {
this.color = '';
this.getColor = () => { return this.color; };
}
printCarColor() {
console.log(this.color);
}
}
var c = new Car();
console.log(c);
If we take a look at the variable c you will notice that function setColor and getColor are created brand new for each instance, and each new copy is placed on each instance whereas function printCarColor is residing on the prototype.
If you want a thousand instances to each be able to make fixed-context method references, you're going to need a thousand separate methods (not one shared), and of course then you're going to have to store each of those thousand separate methods on the instances themselves, thereby defeating the whole point of the single shared prototype.