Javascript 'let' And 'var' In For-loops
Solution 1:
When you use let
the body of the for loop must create a new scope to handle the correct lifetime for the loop variable, however in many cases it is possible to optimise away the extra code and runtime. For example consider this code:
let sum = 0;
let fns = [];
for (let i=0; i < 1000; i++) {
function foo() { sum += i; }
fns.push(foo);
}
When you run it through babeljs you can see the equivalent ES5 code it produces includes a function call in order to preserve the correct variable lifetimes:
var sum = 0;
var fns = [];
var _loop = function _loop(i) {
function foo() {
sum += i;
}
fns.push(foo);
};
for (var i = 0; i < 1000; i++) {
_loop(i);
}
However, babel is intelligent enough that if you don't do anything which requires extending the lifetime of the loop variable it simply uses an ordinary for
loop with the body inline. So your code:
for (let i=0; i < 1000; i++) {
true;
}
can be shown to be exactly equivalent to:
for (var i=0; i < 1000; i++) {
true;
}
My guess would be that something very similar happens internally in Chrome, but they haven't yet optimised out the cases where they don't have to keep the loop variable alive.
It would be interesting to see how the code I used at the top of this example compares in Firefox and Chrome as I suspect they should both end up similarly slow. You should beware of timing things like empty loops as the results can be skewed by optimisation far more than is normal for actual code.
Solution 2:
It's because the let keyword is somewhat new to the specification and is only applicable to the local scope. In Chrome it doesn't seem to be optimized yet, but that should only be a matter of time.
Post a Comment for "Javascript 'let' And 'var' In For-loops"