为什么var声明快于let [英] why var declaration fast than let

查看:112
本文介绍了为什么var声明快于let的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 'use strict'function test(){let t = Date.now();令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();  

div>



运行chrome中的代码,为什么test1比测试快。是我的错误还是我的错?

  50000000 
测试:1146

50000000
test1:148


解决方案

在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>  



loganfsmyth在评论中提到,它通过为循环的每次迭代有效地创建一个新的关闭来实现。



这个功能是新的,可能会占Chrome中的一些性能差异。也就是说,对于您的特定示例,Firefox似乎没有任何区别,因此浏览器似乎可以优化此功能。


'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 

解决方案

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.

这篇关于为什么var声明快于let的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆