Skip to content

Instantly share code, notes, and snippets.

@vsemozhetbyt
Last active January 25, 2017 13:33
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vsemozhetbyt/396eb4b7713accf60ead2fe164e47306 to your computer and use it in GitHub Desktop.
Save vsemozhetbyt/396eb4b7713accf60ead2fe164e47306 to your computer and use it in GitHub Desktop.
Benchmark cycles: var / let / const
/******************************************************************************/
'use strict';
/******************************************************************************/
// via https://twitter.com/bmeurer/status/821804688454680576
console.log(`
// v8 ${process.versions.v8} (Node.js ${process.versions.node})
`);
function forVar_______(a) {
var x = 0;
for (var i = 0, l = a.length; i < l; ++i) x += a[i];
return x;
}
function forLet_______(a) {
let x = 0;
for (let i = 0, l = a.length; i < l; ++i) x += a[i];
return x;
}
function forOfVar_____(a) {
var x = 0;
for (var y of a) x += y;
return x;
}
function forOfLetConst(a) {
let x = 0;
for (const y of a) x += y;
return x;
}
function forEachVar___(a) {
var x = 0;
a.forEach((y) => { x += y; });
return x;
}
function forEachLet___(a) {
let x = 0;
a.forEach((y) => { x += y; });
return x;
}
const a = [];
for (let i = 0; i < 1000; ++i) a[i] = i;
function bench(f) {
for (let i = 0; i < 1000; ++i) f.call(null, a);
}
for (let i = 0; i < 10; ++i) {
bench(forVar_______);
bench(forLet_______);
bench(forOfVar_____);
bench(forOfLetConst);
bench(forEachVar___);
bench(forEachLet___);
}
console.time(forVar_______.name);
bench(forVar_______);
console.timeEnd(forVar_______.name);
console.time(forLet_______.name);
bench(forLet_______);
console.timeEnd(forLet_______.name);
console.time(forOfVar_____.name);
bench(forOfVar_____);
console.timeEnd(forOfVar_____.name);
console.time(forOfLetConst.name);
bench(forOfLetConst);
console.timeEnd(forOfLetConst.name);
console.time(forEachVar___.name);
bench(forEachVar___);
console.timeEnd(forEachVar___.name);
console.time(forEachLet___.name);
bench(forEachLet___);
console.timeEnd(forEachLet___.name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment