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)
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.
For readability and best practices, it's usually better to keep the scope of variables as limited as possible. By using const inside the loop. Having the variable declared with let
outside the loop may lead to bugs because you may be using that variable later.