Why var declaration is quicker 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(); 

execute the code above in chrome, why test1 is faster than test. is this a mistake or a mistake?

 50000000 test: 1146 50000000 test1 : 148 
+3
source share
1 answer

It may be worth noting that in es6, the let keyword in for-loop was designed to solve the notorious closure problem in a loop 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 the comments, he does this by effectively creating a new closure for each iteration of the loop.

This and the fact that this feature is new may explain some of the performance differences observed in Chrome. However, in your specific example, there seems to be no difference in Firefox, so browsers can optimize this.

+3
source

Source: https://habr.com/ru/post/981509/


All Articles