var arr = [
{
"opportunityId": 5943111,
"findingList": [
{
"findingId": 6919
}
],
},
{
"opportunityId": 5943111,
"findingList": [
{
"findingId": 6918,
"findingId": 6917
}
]
}
]
arr.reduce((acc, findingInOpp) => [acc, findingInOpp.findingList.map(({ findingId }) => findingId)],[])
var arr = [
{
"opportunityId": 5943111,
"findingList": [
{
"findingId": 6919
}
],
},
{
"opportunityId": 5943111,
"findingList": [
{
"findingId": 6918,
"findingId": 6917
}
]
}
]
arr.reduce((acc, findingInOpp) => {
findingInOpp.findingList.forEach(({ findingId }) => acc.push(findingId))
return acc
},[])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread operator | |
Push |
Test name | Executions per second |
---|---|
spread operator | 1786017.9 Ops/sec |
Push | 4701227.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The provided benchmark is designed to compare two approaches for flattening an array of objects in JavaScript: using the Array.prototype.reduce()
method with the spread operator (...
) and pushing elements onto an accumulator array. The test measures which approach is faster, but we'll also explore the pros and cons of each approach.
Options Compared
The benchmark compares two options:
push()
method to add elements to an accumulator array in a loop....
): Using the spread operator to create a new array from an existing array or object, and then adding it to the accumulator array.Pros and Cons of Each Approach
Pros:
Cons:
push()
calls....
)Pros:
Cons:
push()
.Library Usage
There are no libraries used in this benchmark. The test code only uses built-in JavaScript features and methods.
Special JS Feature/Syntax
The benchmark uses the spread operator (...
), which is a relatively new feature introduced in ES6 (2015). This syntax allows for more concise and expressive array manipulation, but may not be supported in older browsers or versions of JavaScript.
Other Alternatives
If you're interested in exploring alternative approaches to this benchmark, here are a few options:
Array.prototype.concat()
instead of push()
.Keep in mind that the choice of approach depends on the specific requirements of your project, including performance, code readability, and compatibility with different JavaScript versions and browsers.