v8 JavaScript performance implications of const, let, and var? v8 JavaScript performance implications of const, let, and var? javascript javascript

v8 JavaScript performance implications of const, let, and var?


TL;DR

In theory, an unoptimized version of this loop:

for (let i = 0; i < 500; ++i) {    doSomethingWith(i);}

might be slower than an unoptimized version of the same loop with var:

for (var i = 0; i < 500; ++i) {    doSomethingWith(i);}

because a different i variable is created for each loop iteration with let, whereas there's only one i with var.

Arguing against that is the fact the var is hoisted so it's declared outside the loop whereas the let is only declared within the loop, which may offer an optimization advantage.

In practice, here in 2018, modern JavaScript engines do enough introspection of the loop to know when it can optimize that difference away. (Even before then, odds are your loop was doing enough work that the additional let-related overhead was washed out anyway. But now you don't even have to worry about it.)

Beware synthetic benchmarks as they are extremely easy to get wrong, and trigger JavaScript engine optimizers in ways that real code doesn't (both good and bad ways). However, if you want a synthetic benchmark, here's one: