const range = (from, to) => {
const output = []
for(var x = from; x < to; x++){
output.push(x)
}
return output
}
range(0, 1000).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, 1000).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, 1000).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 | 1603.2 Ops/sec |
with mutation | 43402.7 Ops/sec |
with object assign | 401.7 Ops/sec |
I'll provide an explanation of the provided benchmark.
Benchmark Overview
The benchmark measures the performance of three different approaches for modifying an object in JavaScript:
...
).Object.assign()
to create a new object and assign values to it.Options Compared
The options being compared are:
{ ... }
syntax).Object.assign()
to create a new object and assign values to it.Pros and Cons of Each Approach
Object.assign()
due to the overhead of creating a new object.Library Used
There is no library used in this benchmark. The tests are written in vanilla JavaScript.
Special JS Features/Syntax
The benchmark uses a custom range()
function that returns an array of numbers from 0 to the specified upper limit (to
). This function is not a built-in JavaScript feature, but rather a simple utility function designed for the purposes of this benchmark.