Using arrow functions might be costing you performance

George - May 31 '19 - - Dev Community

Oh, and so might implicit returns…

Background

We all know and love arrow functions, the clean looks, the convenience. But using them does come at a cost.

Firstly, if you are not familiar with arrow functions, this is a simple comparison of how they compare to normal functions.

// Traditional function declaration
function functionName (...parameters) {
    // Do some stuff…
    return result
}

// The same function as an arrow function
const functionName = (...parameters) => {
    // Do some stuff…
    return result
}
Enter fullscreen mode Exit fullscreen mode

Okay, I know what arrow functions are. How are they bad?

JavaScript is compiled at runtime, unlike other languages which require compilation before use. This means that we are relying on the runtime compilation engine to properly interpret and process our code efficiently. This means that different implementations can be processed differently under the hood, despite giving the same outcome.

Comparisons

To test I wrapped the function calls for the functions below in a console.time/console.timeEnd sandwich and passed each one the same variables.

// Traditional function
function foo(bar) {
    return bar
}

// Arrow function
const foo = bar => {
    return bar
}

// Arrow function with implicit return (remember this from the beginning?)
const foo = bar => bar
Enter fullscreen mode Exit fullscreen mode

Results

Traditional function: 0.0746ms
Arrow function: 0.0954ms
Arrow function with implicit return: 0.105ms

Conclusion

Arrow functions and especially arrow functions using implicit returns do take more time to run compared to traditional functions. Implicit returns suffer from the same issues that arrow functions do, in that they take more compilation time. In larger scripts this could feasibly lead to noticeable performance costs, especially if contained within loops.

Does this mean that we should all stop using them then?
Well i'm not going to, and i'm not going to recommend that you stop either. I would hope that everyone is minimizing their code for production. All major minimizers will pre-compile your code in to traditional functions, just for compatibility reasons, negating the performance loss in real world use. If you are experiencing slowdowns in an unminified development environment, then you could consider this as a possible issue. In reality though, a poorly optimized loop will incur many more performance costs than a few arrow functions.

All tests were run 5 times and averaged using Google’s V8 engine running on NodeJs.
Firefox’s SpiderMonkey and Microsoft’s ChakraCore display similar results although were not tested.

. . . . . . . .
Terabox Video Player