猿问

問問用 let 全面取代 var 的話 會性能上差異嗎?

自從之前曾經發生過 var 宣告的變量反而會出 BUG 之後
我本身現在都是用 let

但看了一下 github 上知名的專案似乎都仍然使用 var

所以想問問用 let 全面取代 var 的話 會有性能上差異嗎?
或者缺點?


qq_花开花谢_0
浏览 716回答 2
2回答

梵蒂冈之花

var和let主要是作用域不同,那可以使用现代浏览器都带有的performance api自己测一测。var repeat = 1e8;function benchmark(fn, fname, n){&nbsp; &nbsp; var start = performance.now();&nbsp; &nbsp; for(var i=0;i<n;i++){&nbsp; &nbsp; &nbsp; &nbsp; fn(i);&nbsp; &nbsp; }&nbsp; &nbsp; var end = performance.now();&nbsp; &nbsp; console.log(fname, parseFloat(end-start).toFixed(3), "ms");}benchmark(function(i){&nbsp; &nbsp; if(true){&nbsp; &nbsp; &nbsp; &nbsp; let a = i&nbsp; &nbsp; }}, 'let-with-if', repeat);benchmark(function(i){&nbsp; &nbsp; if(true){&nbsp; &nbsp; &nbsp; &nbsp; var a = i;&nbsp; &nbsp; }}, 'var-with-if', repeat);benchmark(function(i){&nbsp; &nbsp; if(true){}&nbsp; &nbsp; let a = i;}, 'let-without-if', repeat);benchmark(function(i){&nbsp; &nbsp; if(true){}&nbsp; &nbsp; var a = i;}, 'var-without-if', repeat);打开控制台,自己跑一跑就知道了。在我的机器上:let-with-if 60.645 msvar-with-if 429.320 mslet-without-if 430.505 msvar-without-if 425.150 ms

吃鸡游戏

在知乎看过一篇文章挺好的:我用了两个月的时间才理解let
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答