Last active
January 25, 2017 13:33
-
-
Save vsemozhetbyt/396eb4b7713accf60ead2fe164e47306 to your computer and use it in GitHub Desktop.
Benchmark cycles: var / let / const
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************************************************************************/ | |
'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
Table: https://gist.github.com/chicoxyzzy/0ecb281f61120a4704d3313e4d600859#gistcomment-1975047