reduce vs filter (v4)

Revision 4 of this benchmark created on


Setup

const source = Array.from(Array(10000000).keys());

const stage1 = (s) => s % 2 === 0;
const stage2 = (s) => s * 3 % 4 == 0;
const stage3 = (s) => s % 999 === 0;
const stage4 = (s) => s / 2 === 0;

const stages = [
stage1,
stage2,
stage3,
stage4
]

const applyStages = (s) => {
  for (let stage of stages) {
    if (!stage(s)) { return false; }
  }
  return true;
}

const stage1Nodes = (nodes) => nodes.filter(stage1)
const stage2Nodes = (nodes) => nodes.filter(stage2)
const stage3Nodes = (nodes) => nodes.filter(stage3)
const stage4Nodes = (nodes) => nodes.filter(stage4)

Test runner

Ready to run.

Testing in
TestOps/sec
filter
const results1 = []
for (let node of source) {
	if (applyStages(node)) {
  	results1.push(node);
  }
}
ready
reduce
const results2 = [stage1Nodes, stage2Nodes, stage3Nodes, stage4Nodes].reduce((acc, curr) => curr(acc), source);
ready
filter (int only)
let results1 = 0
for (let node of source) {
	if (applyStages(node)) {
  	results1 += 1;
  }
}
ready
for loop
const results1 = []
for (let node of source) {
	if (stage1(node) && stage2(node) && stage3(node) && stage4(node)) {
		results1.push(node);
	}
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.