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 | 2437581.2 Ops/sec |
Using Object.assign | 4733628.0 Ops/sec |
The provided JSON represents a JavaScript microbenchmark test case on MeasureThat.net. The purpose of this benchmark is to compare the performance of two approaches: using the spread operator (also known as the rest-spread syntax) and using Object.assign()
.
What are being compared?
Two different methods for merging two objects in JavaScript:
...
):const finalObject = { ...firstObject, ...secondObject };
This approach uses the spread operator to merge the properties of firstObject
and secondObject
. The resulting object is created by spreading the key-value pairs from both objects into a new object.
Object.assign()
:const finalObject = Object.assign({}, firstObject, secondObject);
This approach uses the Object.assign()
method to create a new object and assigns the properties of firstObject
and secondObject
to it.
Pros and Cons
Using the spread operator:
Pros:
Cons:
Using Object.assign()
:
Pros:
Cons:
Other considerations
When choosing between these two approaches, consider the following factors:
Object.assign()
is a safer bet.Object.assign()
provides an additional layer of flexibility.Library and special JS feature
There are no external libraries used in this benchmark. However, the spread operator syntax was introduced in ECMAScript 2018 (ES8) and is now widely supported across modern browsers and environments.