简体   繁体   English

为什么var声明快于让

[英]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. 在chrome中运行上面的代码,为什么test1比测试快。 is the let' fault or my fault? 是'错误还是我的错?

50000000
test:  1146

50000000
test1 :  148 

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: 值得一提的是,在es6中,for循环中的let关键字被设计用于解决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. 正如@loganfsmyth在注释中提到的那样,它通过为循环的每次迭代有效地创建一个新闭包来实现这一点。

This, and the fact that the feature is new, might account for some of the performance difference seen in Chrome. 这个以及该功能是新功能的事实可能会导致Chrome中出现的部分性能差异。 That said, there seems to be no difference in Firefox for your particular example, so it seems possible for browsers to optimize this. 也就是说,Firefox的特定示例似乎没有区别,因此浏览器似乎可以对此进行优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM