flatMap vs. filter + map

Benchmark created on


Description

Different ways of filtering and mapping a large array.

Preparation HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" referrerpolicy="no-referrer"></script>

Setup

const array = new Array(10000).fill(0).map((zero, index) => index);

Test runner

Ready to run.

Testing in
TestOps/sec
flatMap
array.flatMap((x) => x % 2 === 0 ? [x + 1] : []);
ready
filter + map
array.filter((x) => x % 2 === 0).map((x) => x + 1);
ready
lodash flatMap
_.flatMap(array, (x) => x % 2 === 0 ? [x + 1] : []);
ready
lodash filter + map
_.map(_.filter(array, (x) => x % 2 === 0), (x) => x + 1);
ready
lodash filter + map chain
_.chain(array).filter((x) => x % 2 === 0).map((x) => x + 1).value();
ready

Revisions

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