Using a var
instead of a let
in a for loop was a game changer with Node.js 6 but now it's merely the same performances.
for (var i = 0; i < 10000; i++) {
// ...
}
for (let i = 0; i < 10000; i++) {
// ...
}
Node 6
for var x 156,390 ops/sec ±1.12% (83 runs sampled)
for let x 99,355 ops/sec ±0.80% (89 runs sampled)
Fastest is for var
Node 8
for var x 126,389 ops/sec ±1.26% (86 runs sampled)
for let x 131,086 ops/sec ±1.27% (91 runs sampled)
Fastest is for let
Node 10
for let x 141,522 ops/sec ±0.93% (89 runs sampled)
for var x 141,682 ops/sec ±0.75% (93 runs sampled)
Fastest is for var,for let
Node 12
for let x 142,272 ops/sec ±0.85% (87 runs sampled)
for var x 149,323 ops/sec ±0.48% (93 runs sampled)
Fastest is for var
Node 14
for let x 143,337 ops/sec ±0.86% (90 runs sampled)
for var x 150,583 ops/sec ±0.69% (94 runs sampled)
Fastest is for var
Node 16
for let x 153,116 ops/sec ±0.87% (88 runs sampled)
for var x 157,170 ops/sec ±0.53% (94 runs sampled)
Fastest is for var
Today it all depends on what you do with the variable. Let is scoped to the block context, while var is hoisted. If you don't capture the variable, the let will be hoisted to the same place as the var, so there's literally no difference. If you do capture the variable, the var will be shared by each capture from each iteration; while the let will be captured independently for each iteration. There's a cost to keeping those let values independent.