const a = [Array(1000)].map(() => ({
nested: Array.from({length: 40}, () => Math.floor(Math.random() * 40))
}));
let b = [];
a.forEach((item) => {
b = b.concat(item.nested);
});
const a = [Array(1000)].map(() => ({
nested: Array.from({length: 40}, () => Math.floor(Math.random() * 40))
}));
const b = a.reduce((acc, item) => {
acc.push(item.nested);
return acc
}, []);
const a = [Array(1000)].map(() => ({
nested: Array.from({length: 40}, () => Math.floor(Math.random() * 40))
}));
const b = a.reduce((acc, item) => {
acc.concat(item.nested);
return acc
}, []);
const a = [Array(1000)].map(() => ({
nested: Array.from({length: 40}, () => Math.floor(Math.random() * 40))
}));
let b = [];
a.forEach((item) => {
b.push(item.nested);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach concat | |
Reduce push | |
Reduce concat | |
forEach push |
Test name | Executions per second |
---|---|
forEach concat | 19.9 Ops/sec |
Reduce push | 56.2 Ops/sec |
Reduce concat | 56.9 Ops/sec |
forEach push | 52.5 Ops/sec |
Let's break down the benchmark and its individual test cases.
Benchmark Definition
The benchmark is designed to compare the performance of different approaches for concatenating arrays in JavaScript. Specifically, it tests four different methods:
forEach concat
Reduce push
Reduce concat
forEach push
Each method is implemented slightly differently:
forEach concat
: uses the concat
method to concatenate the nested
array of each object.Reduce push
: uses the reduce
method with a custom callback function that pushes the elements of item.nested
onto the accumulator using the spread operator (...
).Reduce concat
: uses the reduce
method and concatenates the elements of item.nested
directly using the +
operator.forEach push
: uses the push
method to add each element of item.nested
to the end of the accumulator array.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
concat
.+
.push
for each element.Library and Special JS Features
None of these approaches rely on any specific libraries or special JavaScript features beyond standard JavaScript syntax.
Other Considerations
When choosing an approach, consider the following factors:
forEach concat
might be a better choice.Reduce push
or Reduce concat
might be a better fit.Reduce push
and Reduce concat
are likely to perform better.Alternatives
Other alternatives for concatenating arrays in JavaScript include:
Array.prototype.push.apply()
method.Array.from()
and then pushing elements onto it.concat
function that's optimized for performance.Keep in mind that these alternatives might not be as concise or readable as the approaches tested in this benchmark.