Skip to content

Instantly share code, notes, and snippets.

@bmeurer
Created November 7, 2017 09:06
Show Gist options
  • Save bmeurer/bcc4200bab03dabefd38e324f5d1b3b6 to your computer and use it in GitHub Desktop.
Save bmeurer/bcc4200bab03dabefd38e324f5d1b3b6 to your computer and use it in GitHub Desktop.
// Microbenchmark to investigate https://twitter.com/DasSurma/status/927324384238473222
var isEvenNum = (num = 1) => num !== 0 && num % 2 === 0;
var sqrNum = num => num * num;
var N = 1000;
var arr = [];
for (n = 1; n <= 10000; ++n) arr.push(n);
function multiloops() {
var result;
for (var i = 0; i < N; ++i) {
result = arr.filter(isEvenNum).map(sqrNum);
}
return result;
}
console.time('multiloops');
multiloops();
console.timeEnd('multiloops');
function reduce() {
var result;
for (var i = 0; i < N; ++i) {
result = arr.reduce((accum, num) => {
if (isEvenNum(num)) accum.push(sqrNum(num));
return accum;
}, []);
}
return result;
}
console.time('reduce');
reduce();
console.timeEnd('reduce');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment