var raw = new Array(250).fill({
id: 'gid://something/Something/something',
handle: 'something',
name: 'Something',
categories: ['SOMETHING'],
lastViewedAt: '2022-03-18T21:30:18Z',
isPinned: false,
});
const flatMapped = raw.flatMap(({ id, categories, handle, name, lastViewedAt, isPinned }) => {
if (categories.length === 0) {
return [];
}
return {
category: categories[0],
handle,
url: "https://google.com/",
name,
lastViewedAt: lastViewedAt == null ? null : new Date(lastViewedAt),
author: "someone",
isPinned,
type: "something",
gid: id,
};
});
const reduced = raw.reduce(function (array, { id, categories, handle, name, lastViewedAt, isPinned }) {
if (categories.length === 0) {
return array;
}
array.push({
category: categories[0],
handle,
url: "https://google.com/",
name,
lastViewedAt: lastViewedAt == null ? null : new Date(lastViewedAt),
author: "someone",
isPinned,
type: "something",
gid: id,
});
return array;
}, []);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
flatMap | |
reduce |
Test name | Executions per second |
---|---|
flatMap | 15177.9 Ops/sec |
reduce | 17209.0 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark involves two test cases: reduce
and flatMap
. Both tests are designed to measure the performance of these two methods on an array of objects.
Test Cases
The first test case, "flatMap", uses the flatMap()
method to transform each element in the input array into a new array with the same length. The transformed array is then returned as the result of the benchmark.
The second test case, "reduce", uses the reduce()
method to iterate over the input array and accumulate a value that represents the sum of all elements in the array. In this case, the accumulator is an empty array []
.
Options Compared
Two options are compared:
Pros and Cons
flatMap()
for large arrays due to function call overhead.Library and Purpose
In both test cases, no specific library is used. The flatMap()
method is a native JavaScript method that uses the spread operator (...
) under the hood, while the reduce()
method is also a native JavaScript method.
Special JS Feature or Syntax
No special JS feature or syntax is used in these benchmark cases.
Other Considerations
When choosing between flatMap()
and reduce()
, consider the following:
flatMap()
might be a better choice.reduce()
might be a better choice.flatMap()
or optimizing your code using techniques like memoization.Alternatives
Other alternatives that can be used in place of flatMap()
and reduce()
include:
flatMap()
, but returns an array with the same length as the input.: Iterates over each element in the input array, but does not accumulate values like
reduce()`.: Returns a new array with only elements that pass a test (like
categories.length > 0`).Keep in mind that these alternatives may have different performance characteristics and use cases compared to flatMap()
and reduce()
.