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 | 0.2 Ops/sec |
with mutation | 3846.2 Ops/sec |
with object assign | 155.8 Ops/sec |
Let's dive into the benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares the performance of three approaches for reducing an object in JavaScript:
Object.assign()
method to merge two objects, where one of them is the original object and the other is an object with a single property.{...}
) to create a new object that includes all the properties of the original object.Options Compared
The benchmark compares these three approaches because they have different performance characteristics:
Pros and Cons
Here are the pros and cons of each approach:
Library and Special JS Feature
The benchmark uses none of a library, but it does use the Object.assign()
method, which is a built-in JavaScript function.
Special JS Feature
There are no special JavaScript features used in this benchmark. The code relies on standard JavaScript syntax and semantics.
Other Alternatives
If you were to rewrite this benchmark, you could consider using alternative approaches:
reduce()
or forEach()
to iterate over the range and create a new object.Keep in mind that these alternatives might have different performance characteristics compared to the original benchmark.