I was testing performance differences between const
and var
in Javascript, when I noticed that const
is slower than var
.
I wrote a script to time const
and var
and compare them. It tests if const
is faster 1000 times. const
is faster only about 13% of the time.
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())
So, my question is, why is a variable declaration with var
faster than one with const
?
Once I ran a few tests with jsbench, as suggested in the comments, I realized that the performance could vary, and that my timing method was flawed.
JSBench: https://jsben.ch/eAiAk
So, there is no real time difference between const
and var
.