Is there a performance difference between 'let' and 'var' in JavaScript

前端 未结 5 1370
慢半拍i
慢半拍i 2020-11-28 05:23

The difference between these two keywords in terms of scoping has already been thoroughly discussed here, but I was wondering if there is any kind of performance difference

5条回答
  •  萌比男神i
    2020-11-28 05:48

    Inside loops let is significantly slower see: https://jsperf.com/let-vs-var-loop

    838,602 ±0.77% 61% slower

    (function() {
    
      "use strict";
      var a=0;
      for(let i=0;i<100;i++) {
        a+=i;
      }
    })();
    

    vs.

    2,136,387 ±1.09% fastest

    (function() {
    
      "use strict";
      var a=0;
      for(var i=0;i<100;i++) {
        a+=i;
      }
    })();
    

    This is because when using let, for every loop iteration the variable is scoped. example:

    for (let i = 0; i < 10 ; i++) {
        setTimeout(function() { console.log(i); }, 100 * i);
    }
    

    yields to

    0,1,2,3,4,5,6,7,8,9
    

    using var yields to

    10,10,10,10,10,10,10,10,10,10
    

    If you want to have the same result, but using var you have to use an IIFE:

    for (var i = 0; i < 10; i++) {
      // capture the current state of 'i'
      // by invoking a function with its current value
      (function(i) {
        setTimeout(function() { console.log(i); }, 100 * i);
      })(i);
    }
    

    which on the other hand is significantly slower than using let.

提交回复
热议问题