flatMap vs filterMap vs map.filter (v3)

Revision 3 of this benchmark created on


Description

https://twitter.com/TkDodo/status/1639888927799623681

Setup

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

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 (2000)
const users = big.flatMap(x => x.kind === "user" ? [x] : [])
ready
filterMap (2000)
const users = filterMap(big, x => x.kind === "user" ? x : undefined)
ready
flatMap
const users = small.flatMap(x => x.kind === "user" ? [x] : [])
ready
filterMap
const users = filterMap(small, x => x.kind === "user" ? x : undefined)
ready
map.filter (2000)
const users = big.map(x => x).filter(x => x.kind === "user");
ready
map.filter
const users = small.map(x => x).filter(x => x.kind === "user");
ready

Revisions

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