Skip to content

Instantly share code, notes, and snippets.

@Aschen
Created July 18, 2022 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aschen/7fc5a1c219be2e05cacbe6c1eb33b5ac to your computer and use it in GitHub Desktop.
Save Aschen/7fc5a1c219be2e05cacbe6c1eb33b5ac to your computer and use it in GitHub Desktop.
For loop with `var` vs `let`

For loop with var vs let

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++) {
  // ...
}

image

Results

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
const { Benchmark } = require("benchmark");
var suite = new Benchmark.Suite();
const array = [];
for (var i = 0; i < 1000; i++) {
array.push(i);
}
let ret;
// add tests
suite
.add("for var", function () {
ret = [];
for (var i = 0; i < array.length; i++) {
ret.push(i);
}
})
.add("for let", function () {
ret = [];
for (let i = 0; i < array.length; i++) {
ret.push(i);
}
})
// add listeners
.on("cycle", function (event) {
console.log(String(event.target));
})
.on("complete", function () {
console.log("Fastest is " + this.filter("fastest").map("name"));
})
// run async
.run();
@verwaest
Copy link

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.

@Aschen
Copy link
Author

Aschen commented Jul 25, 2022

So it's this (small) cost that we can see in this benchmark right?

Also, using var could result in a higher memory usage ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment