const range = (from, to) => {
const output = []
for(var x = from; x < to; x++){
output.push(x)
}
return output
}
range(0, 10000).reduce((acc, num) => {
return {
acc,
[num]: num
}
}, {})
const range = (from, to) => {
const output = []
for(var x = from; x < to; x++){
output.push(x)
}
return output
}
range(0, 10000).reduce((acc, num) => {
acc[num] = num
return acc
}, {})
const range = (from, to) => {
const output = []
for(var x = from; x < to; x++){
output.push(x)
}
return output
}
range(0, 10000).reduce((acc, num) => {
return Object.assign(acc, {[num]: num})
}, {})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
with spread operator | |
with mutation | |
with object assign |
Test name | Executions per second |
---|---|
with spread operator | 129.5 Ops/sec |
with mutation | 16887.0 Ops/sec |
with object assign | 408.1 Ops/sec |
The benchmark tests the performance of three different approaches for constructing an object while processing a range of numbers from 0 to 9999 using the reduce
method. The methods being compared are:
...
)Object.assign()
range(0, 10000).reduce((acc, num) => {
return {
...acc,
[num]: num
};
}, {});
Description: This method utilizes the spread operator to create a new object for every iteration in the reduce
function. It expands the contents of the existing acc
object (accumulator) into a new object while adding the current number as a key-value pair.
Pros:
Cons:
range(0, 10000).reduce((acc, num) => {
acc[num] = num;
return acc;
}, {});
Description: This approach directly modifies the acc
object by adding new key-value pairs to it.
Pros:
Cons:
Object.assign()
range(0, 10000).reduce((acc, num) => {
return Object.assign(acc, {[num]: num});
}, {});
Description: This method uses Object.assign()
to copy properties from a new object (with the current number as a key) into the accumulator.
Pros:
Object.assign
can be seen as a non-destructive operation on the surface.Cons:
The benchmark results show the number of executions per second for each method:
Object.assign()
might be more suitable.lodash
which provides functional utilities for deep merging and cloning objects while considering performance. Moreover, utilizing modern JavaScript features such as Map
or Set
could also be relevant, depending on the specific requirements of the task (e.g., needing unique keys).This benchmark illustrates the trade-offs between different JavaScript object construction techniques within a functional programming context, emphasizing the importance of selecting the right method based on use case requirements.