flatMap vs filterMap

Benchmark created on


Setup

const small = [{kind: "user", data: {}},{kind: "agent", data: {}}]
const big = Array.from({length: 1000}).flatMap(() => small)

export function filterMap(array, map) {
  if (array.length === 0) {
    return array
  }
  const out = []
  for (const item of array) {
    const mapped = map(item)
    if (mapped !== undefined) {
      out.push(mapped)
    }
  }
  return out
}

Test runner

Ready to run.

Testing in
TestOps/sec
flatMap
const users = big.flatMap(x => x.kind === "user" ? [x] : [])
ready
filterMap
const users = filterMap(big, x => x.kind === "user" ? x : undefined)
ready
small flatMap
const users = small.flatMap(x => x.kind === "user" ? [x] : [])
ready
small filterMap
const users = filterMap(small, x => x.kind === "user" ? x : undefined)
ready

Revisions

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