const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = {
firstObject,
secondObject
};
const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
function newState(a, b) {
return Object.assign({}, a, b);
}
const finalObject = newState(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 | 2426056.8 Ops/sec |
Using Object.assign | 3624066.2 Ops/sec |
This benchmark compares two ways to merge objects in JavaScript:
1. Using the Spread Operator (...
):
const finalObject = {...firstObject, ...secondObject}
firstObject
and secondObject
into a new object called finalObject
.2. Using Object.assign()
:
function newState(a, b) {
return Object.assign({}, a, b);
}
const finalObject = newState(firstObject, secondObject);
Object.assign()
method to create a new object and copy properties from the first two objects (firstObject
and secondObject
) into it. The empty object ({}
) as the first argument ensures that a new object is created rather than modifying one of the existing ones.Pros and Cons:
Spread Operator (...
):
Object.assign()
:
Other Considerations:
_.merge()
) provide more advanced object merging functionalities, including deep merging and custom merge strategies.In Conclusion:
While the spread operator offers a cleaner syntax for simple object merging, Object.assign()
provides more flexibility and control, especially when dealing with complex or nested objects. The benchmark results suggest that for this particular scenario (`Object.assign``) is slightly faster. However, in many real-world applications, the performance difference may be negligible.