Skip to content

Instantly share code, notes, and snippets.

@vsemozhetbyt
Last active January 19, 2017 17:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vsemozhetbyt/7f6db3f73dfec8ac08bcfc81b1b11cbb to your computer and use it in GitHub Desktop.
Save vsemozhetbyt/7f6db3f73dfec8ac08bcfc81b1b11cbb to your computer and use it in GitHub Desktop.
Benchmark cycles (var)
/******************************************************************************/
'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');
@vsemozhetbyt
Copy link
Author

vsemozhetbyt commented Jan 19, 2017

See this more resumptive benchmark with some results in the comments for several v8 / Node.js versions.

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