const firstObject = { sampleData: 'Hello world', withMore: 'Example Data', andWith: 2000 }
const secondObject = { moreData: 'foo bar' }
const finalObject = {
firstObject,
secondObject
};
const firstObject = { sampleData: 'Hello world', withMore: 'Example Data', andWith: 2000 }
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 | 30998330.0 Ops/sec |
Using Object.assign | 18369130.0 Ops/sec |
In the provided benchmark, two different JavaScript techniques for merging objects are compared: the spread operator (...
) and the Object.assign
method. Each approach is evaluated based on its performance in terms of execution speed, measured by the number of executions per second.
Using the Spread Operator (...
):
Code:
const finalObject = {
...firstObject,
...secondObject
};
Pros:
Cons:
Using Object.assign()
:
Code:
const finalObject = Object.assign({}, firstObject, secondObject);
Pros:
Object.assign()
is widely supported in many JavaScript environments, including older versions of browsers.Cons:
The benchmark results indicate that the spread operator outperforms Object.assign
significantly:
This performance difference suggests that while both methods achieve similar outcomes in merging objects, the spread operator does so more efficiently in the tested environment.
Besides the two techniques examined, other alternatives for merging objects may include:
In conclusion, both the spread operator and Object.assign()
are valid approaches for merging objects in JavaScript. The choice between them may depend on the specific use case, readability, compatibility needs, and performance demands for the particular JavaScript environment being targeted. However, the benchmark data suggests that the spread operator is currently the more performant option in the latest browsers.