Why is chrome slow when using let inside for loop?

Published on Author Code Father

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);

That’s more work. If you don’t need a new i for each loop, use let outside the loop.

We can expect that now that everything but modules has been implemented, V8 will probably improve optimization of the new stuff, but it’s not surprising that functionality should be initially prioritized over optimization.

It’s great that other engines have already done the optimization, but the V8 team apparently just haven’t got there yet.

Comments

comments