Skip to content

Instantly share code, notes, and snippets.

@akx
Last active May 22, 2017 16:26
Show Gist options
  • Select an option

  • Save akx/98f822fc0658bae305b8a049bb19e39f to your computer and use it in GitHub Desktop.

Select an option

Save akx/98f822fc0658bae305b8a049bb19e39f to your computer and use it in GitHub Desktop.
for vs foreach
/**
$ node --version
v7.10.0
$ node arrben.js
foreach 2294.22208
for 1342.5684099999999
*/
const benchmark = (name, fn, n = 100) => {
const startTime = process.hrtime();
for(var i = 0; i < n; i++) {
fn();
}
const diff = process.hrtime(startTime);
const usec = diff[0] * 1e9 + diff[1];
const time = (usec / 1000) / n;
console.log(name, time);
};
const arr = new Array(100000).fill(null).map((v, i) => i);
const fa = () => {
const a = arr;
let x = 0;
a.forEach((v) => {
if(v % 8 === 0) x += v;
});
return x;
};
const fb = () => {
const a = arr, l = a.length;
let x = 0;
for(var i = 0; i < l; i++) {
if(a[i] % 8 === 0) x += a[i];
}
return x;
};
benchmark('foreach', fa);
benchmark('for', fb);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment