Why is using `let` inside a `for` loop so slow on Chrome? Why is using `let` inside a `for` loop so slow on Chrome? google-chrome google-chrome

Why is using `let` inside a `for` loop so slow on Chrome?


Update: June 2018: Chrome now optimizes this much better than it did when this question and answer were first posted; there's no longer any appreciable penalty for using let in the for if you aren't creating functions in the loop (and if you are, the benefits are worth the cost).


Because a new i is created for each iteration of the loop, so that closures created within the loop close over the i for that iteration. This is covered by the specification in the algorithm for the evaluation of a for loop body, which describes creating a new variable environment per loop iteration.

Example:

for (let i = 0; i < 5; ++i) {  setTimeout(function() {    console.log("i = " + i);  }, i * 50);}// vs.setTimeout(function() {  let j;  for (j = 0; j < 5; ++j) {    setTimeout(function() {      console.log("j = " + j);    }, j * 50);  }}, 400);