Zhaowei
Zhaowei

Reputation: 323

why var declaration fast than let

'use strict'

function test() {
  let t = Date.now();
  let p = 0;
  for (let i = 0; i < 100000000; i++) {
    p += i % 2;
  }
  console.log(p)
  console.log('test: ', Date.now() - t);
}

function test1() {
  var t = Date.now();
  var p = 0;
  for (var i = 0; i < 100000000; i++) {
    p += i % 2;
  }
  console.log(p)
  console.log('test1 : ', Date.now() - t);
}

test();
test1();

run the code above in chrome, why test1 is fast than test. is the let' fault or my fault?

50000000
test:  1146

50000000
test1 :  148 

Upvotes: 3

Views: 207

Answers (1)

jib
jib

Reputation: 42500

It might be worth mentioning that in es6 the let keyword in a for-loop has been designed to solve the notorious closure in a loop problem in JavaScript:

var log = msg => div.innerHTML += msg + "<br>";

for (var i=0; i < 3; i++) {
  Promise.resolve().then(() => log(i)); // 3, 3, 3
}
for (let i=0; i < 3; i++) {
  Promise.resolve().then(() => log(i)); // 0, 1, 2
}
<div id="div"></div>

As @loganfsmyth mentions in comments, it does this by effectively creating a new closure for each iteration of the loop.

This, and the fact that the feature is new, might account for some of the performance difference seen in Chrome. That said, there seems to be no difference in Firefox for your particular example, so it seems possible for browsers to optimize this.

Upvotes: 3

Related Questions