为什么 const 比 var 慢?

Why is const slower than var?

我在 Javascript 中测试 constvar 之间的性能差异时,我注意到 constvar 慢。

我写了一个脚本来计时 constvar 并比较它们。它测试 const 是否快 1000 倍。 const 只有大约 13% 的时间更快。

function executionTime(code) {
  var t0 = performance.now()
  code()
  var t1 = performance.now()
  return t1 - t0
}

function test() {
    
  var results = [0, 0] // one, two - Which one is faster?
    
  for (var i = 0; i < 999; i++) {
    var one = executionTime(function() {
      const x = 'x'
    })

    var two = executionTime(function() {
      var x = 'x'
    })
        
    if (one > two) {
      results[0]++
    } else {
      results[1]++
    }
  }
    
  return ((results[0] < results[1]) ? 'Const is slower': 'Var is slower') + ' - const was faster ' + results[0] + ' times, and var was faster ' + results[1] + ' times'
}

console.log(test())

所以,我的问题是,为什么 var 的变量声明比 const 的变量声明快?

一旦我 运行 按照评论中的建议使用 jsbench 进行了一些测试,我意识到性能可能会有所不同,并且我的计时方法存在缺陷。

JSBench:https://jsben.ch/eAiAk

因此,constvar之间没有实时差异。