Nickolai Nickolai - 6 months ago 18
Javascript Question

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

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 between the two, and if so, is it negligible, or at what point would it become significant?

Answer

After testing this on http://jsperf.com, I got the following results: jsperf has been down for a while; see the replacing code below.

To check this, I'll use the following performance test:

var i;

/**
 * Finds the performance for a given function
 * function fn the function to be executed
 * int n the amount of times to repeat
 * return array [time for n iterations, average execution frequency (executions per second)]
 */
function getPerf(fn, n) {
  var t0, t1;
  t0 = performance.now();
  for (var i = 0; i < n; i++) {
    fn()
  }
  t1 = performance.now();
  return [parseFloat((t1 - t0).toFixed(3)), parseFloat((repeat * 1000 / (t1 - t0)).toFixed(3))];
}

var repeat = 100000000;
var msg = '';

//-------inside a scope------------
var letperf1 = getPerf(function() {
  if (true) {
    let a = 1;
  }
}, repeat);
msg += '<code>let</code> inside an if() takes ' + letperf1[0] + ' ms for ' + repeat + ' iterations (' + letperf1[1] + ' per sec).<br>'

var varperf1 = getPerf(function() {
  if (true) {
    var a = 1;
  }
}, repeat);
msg += '<code>var</code> inside an if() takes ' + letperf1[0] + ' ms for ' + repeat + ' iterations (' + letperf1[1] + ' per sec).<br>'

//-------outside a scope-----------

var letperf1 = getPerf(function() {
  if (true) {}
  let a = 1;
}, repeat);
msg += '<code>let</code> outside an if() takes ' + letperf1[0] + ' ms for ' + repeat + ' iterations (' + letperf1[1] + ' per sec).<br>'

var varperf1 = getPerf(function() {
  if (true) {}
  var a = 1;
}, repeat);
msg += '<code>var</code> outside an if() takes ' + letperf1[0] + ' ms for ' + repeat + ' iterations (' + letperf1[1] + ' per sec).<br>'

document.getElementById('out').innerHTML = msg
<output id="out" style="font-family: monospace;white-space: pre-wrap;"></output>

After testing this in Chrome and IE11 and MSEdge, this shows that both are identical, both inside and outside an if scope, which does affect the functionality of let differently from var, but apparently not the performance. Press the big blue button to see for yourself in your favourite browser.

Currently let has support from only newer browsers, but older browsers are still being used relatively much, which would be a reason to generally not use it yet. If you want to use it somewhere where older browsers wouldn't function otherwise, there should be no problem with it.

Edit: revamped answer since jsperf is not working (see revision history for old version).

Comments