Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 JavaScript - const inside or let outside loop?

For performance purposes, I want to know what the difference is in ES6 JavaScript between:

var list = [...];
let item; //let outside the loop
for (let i = 0; i < list.length; i++) {
    item = list[i];
}

and

var list = [...];
for (let i = 0; i < list.length; i++) {
    const item = list[i]; //const inside the loop
}

Assume that the item variable is intended to remain constant inside the loop.

Is one recommended? What are the pros and cons relative to performance for each? Does GC handle them differently?

Note that this is micro-optimization. Furthermore, performance is subjective to the JS engine being used.. (see answers)

like image 553
Max K Avatar asked Jun 12 '18 01:06

Max K


1 Answers

It's going to be difficult to give a definitive answer considering that different browsers have vastly different internal implementations. There could very likely be zero difference. Prior to execution, Javascript in the browser is compiled by the internal JIT compiler, which will very likely recognise a redundant variable declaration inside a loop and optimise it out, like any other good compiler. let and const will definitely affect this, I'd say const would make optimisation out of the loop even more likely considering the compiler can instantly see that it's an immutable atomic variable specific to the inner loop scope. It would also likely unroll performance intensive loops as well. Javascript has a few other performance quirks though where accessing variables in higher scopes incurs a minor performance penalty, I remember looking into that a long time ago when doing gamdev in the browser. That might not be current anymore, but it was a few years ago.

As others have pointed out, unless profiling has already indicated that this is a serious bottleneck in your application, it is premature optimisation. I'd be extremely shocked if optimising this could possibly contribute any significant performance benefits. If performance in this area matters, best advice is to profile different scenarios yourself and decide what is best for your use case.

like image 77
ajxs Avatar answered Sep 21 '22 15:09

ajxs