Keep

Benchmark created on


Setup

const as = [];
for (let i = 0; i < 1000; i++) {
	as.push(i);
}

function keep(arr, f) {
  return arr.map(f).filter((b) => b !== null);
}

function keep2(arr, f) {
  return arr.reduce((result, a) => {
    const b = f(a);
    if (b !== null) {
      result.push(b);
    }
    return result;
  }, []);
}

function keep3(arr, f) {
  const result = [];
  for (const a of arr) {
    const b = f(a);
    if (b !== null) {
      result.push(b);
    }
  }
  return result;
}

function mogrify(x) {
	const r = Math.random();
	if (r > 0) {
		return x + (x * r);
	} else {
		return null;
	}
}

Test runner

Ready to run.

Testing in
TestOps/sec
map + filter
keep(as, mogrify);
ready
reduce
keep2(as, mogrify);
ready
for/of
keep3(as, mogrify);
ready

Revisions

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