When you do
for (let i = 0; i < 1000000; i += 1) { }
The value of i in each cycle of the cycle is a separate link, which is useful when using the value of i in an asynchronous callback. It is slower, but can be faster than alternatives in this use case.
If instead you use
let j; for (j = 0; j < 1000000; ++j) { }
you will only have one reference to the value, and it will be as fast as with var.
Try using the following code
console.time("let i"); for (let i = 0; i < 10000000; ++i) { } console.timeEnd("let i"); console.time("let j"); let j; for (j = 0; j < 10000000; ++j) { } console.timeEnd("let j"); console.time("var k"); for (var k = 0; k < 10000000; ++k) { } console.timeEnd("var k");
this will give results like
let i: 91ms let j: 25ms var k: 27ms
where the equally fast var value is given clearly when used correctly.
Also, to see the difference in asynchronous behavior, try
for (let i = 0; i < 3; ++i) { setImmediate(() => { console.log(i) }); } let j; for (j = 0; j < 3; ++j) { setImmediate(() => { console.log(j) }); } for (var k = 0; k < 3; ++k) { setImmediate(() => { console.log(k) }); }
which will output
0 1 2 3 3 3 3 3 3
as in every cycle of the cycle, in order for me to value I was a unique link, which causes insignificant overhead, whereas for the other two cycles it is the same link.
source share