Skip to content

Performance rule js-flatmap-filter doesn't appear to provide a performance improvement #1466

Description

@nspector

Hi! I was evaluating this rule:

Performance: .map().filter(Boolean) loops twice

https://react.doctor/docs/rules/react-doctor/js-flatmap-filter

Since this is categorized as a performance optimization, I wanted to verify the claim with a simple benchmark.

I tested three implementations over an array of 10,000 items:

// map + filter
DATA.map((_, i) => i % 2 ? i : null).filter(Boolean)

// flatMap
DATA.flatMap((_, i) => i % 2 ? i : [])

// reduce
DATA.reduce((acc, _, i) => {
  if (i % 2) {
    acc.push(i);
  }
  return acc;
}, [])

On my machine, the results were approximately:

ImplementationOps/s
map().filter(Boolean)~20k
flatMap()~15k
reduce()~75k

In this benchmark, flatMap() was slower than map().filter(Boolean) despite only making a single pass.

I realize this is only one benchmark and that performance varies between JavaScript engines. However, since this rule is categorized as a performance optimization, I expected flatMap() to consistently outperform the two-pass version, which wasn't the case here.

Given that, I wonder if this rule should either:

  • be categorized as a readability or style recommendation rather than a performance optimization
  • include evidence or caveats showing when flatMap() is actually expected to improve performance
  • updated to recommend alternatives such as reduce()

For reference, here's the benchmark I used:
https://jsbm.dev/5L2w7oKTpySSb (including map by itself)

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions