const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = {
firstObject,
secondObject,
}
const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = Object.assign({}, firstObject, secondObject)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign |
Test name | Executions per second |
---|---|
Using the spread operator | 661531.4 Ops/sec |
Using Object.assign | 1184554.0 Ops/sec |
Let's break down what's being tested in this JavaScript microbenchmark.
Benchmark Definition
The benchmark is comparing two approaches to merge objects:
const finalObject = { ...firstObject, ...secondObject }
const finalObject = Object.assign({}, firstObject, secondObject)
What's being tested?
The benchmark is testing the performance difference between using the object spread operator and Object.assign()
to merge two objects.
Options compared
Two options are being compared:
{ ... }
) to create a new object with properties from both firstObject
and secondObject
.Object.assign()
method to merge two objects.Pros and Cons of each approach
Object spread operator (Rest/spread syntax)
Pros:
Math.max(..., ...)
)Cons:
Object.assign()
Pros:
Cons:
Other considerations
The benchmark also considers the library being used (in this case, none are specified), which means that any performance differences can be attributed solely to the JavaScript engine and its optimizations.
There are no special JS features or syntax mentioned in this benchmark. Both approaches are standard and widely supported.
Alternative approaches
If you want to explore alternative approaches, here are a few:
const { sampleData, moreData } = firstObject; const finalObject = { ...{ sampleData }, ...{ moreData } };
reduce()
method: const finalObject = Object.keys(firstObject).reduce((acc, key) => ({ ...acc, [key]: firstObject[key] }), {})
Keep in mind that these alternatives might not be as concise or readable as the original approaches, but they can provide interesting performance insights.