Last active
January 19, 2017 17:03
-
-
Save vsemozhetbyt/7f6db3f73dfec8ac08bcfc81b1b11cbb to your computer and use it in GitHub Desktop.
Benchmark cycles (var)
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 f1(a) { | |
var x = 0; | |
for (var i = 0, l = a.length; i < l; ++i) x += a[i]; | |
return x; | |
} | |
function f2(a) { | |
var x = 0; | |
for (var y of a) x += y; | |
return x; | |
} | |
function f3(a) { | |
var 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(f1); | |
bench(f2); | |
bench(f3); | |
} | |
console.time('for '); | |
bench(f1); | |
console.timeEnd('for '); | |
console.time('for-of '); | |
bench(f2); | |
console.timeEnd('for-of '); | |
console.time('forEach'); | |
bench(f3); | |
console.timeEnd('forEach'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See this more resumptive benchmark with some results in the comments for several v8 / Node.js versions.