flatMap vs filter and map (v3)

Revision 3 of this benchmark created on


Description

exploring whether intermediary array costs can be circumvented.

Setup

const persons = Array.from({ length: 1_000_000 }, (_, i) => ({
  name: `Person${i}`,
  age: Math.floor(Math.random() * 100)
}));

Test runner

Ready to run.

Testing in
TestOps/sec
Filter and map
persons.filter(p => p.age > 60).map(p => p.name);
ready
flatMap
persons.flatMap(({ age, name }) => age > 60 ? [name] : []);
ready
flatMap2
const dummy = []

persons.flatMap(({ age, name }) => age > 60 ? name : dummy);
ready
flatMap3


persons.flatMap(({ age, name }) => age > 60 ? name : []);
ready
No array helpers
const result = [];
for (let person of persons) {
	if (person.age > 60) {
		result.push(person.name);
	}
}
ready
Encapsulated + predicate, map functions
function filterAndMap(people, predicate, map) {
	const result = [];
	for (let person of people) {
		if (predicate(person)) {
			result.push(map(person));
		}
	}
	return result;
}

filterAndMap(persons, p => p.age > 60, p => p.name);
ready
Encapsulated with hardcoded logic
function filterAndMap(people) {
	const result = [];
	for (let person of people) {
		if (person.age > 60) {
			result.push(person.name);
		}
	}
	return result;
}

filterAndMap(persons);
ready

Revisions

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