const firstObject = {};
const secondObject = {};
for (let i = 0; i < 1000; i++) {
firstObject[i] = i;
secondObject[i + 500] = i;
}
window.firstObject = firstObject;
window.secondObject = secondObject;
const finalObject = {
window.firstObject,
window.secondObject
};
const finalObject = Object.assign({}, window.firstObject, window.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 | 16292.9 Ops/sec |
Using Object.assign | 16134.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark compares two approaches for merging objects in JavaScript:
...
): This syntax was introduced in ECMAScript 2018 (ES2018) as a way to expand an object literal into multiple arguments.Pros and Cons
Spread Operator
Pros:
Cons:
obj['prop']
instead of obj.prop
)Object.assign()
Pros:
Cons:
Other Considerations
When choosing between these two approaches, consider the following factors:
Library Usage
In this benchmark, both test cases use built-in JavaScript methods (Object.assign() for one case, and the spread operator for another). There are no external libraries involved in these tests.
Special JS Features
There are a few special features in these tests:
...
operator is used to expand an object literal into multiple arguments. This syntax relies on ECMAScript 2018 (ES2018) support.Alternatives
Other methods you might consider when merging objects include:
Object.keys()
method to iterate over properties and manually merge themmerge
function)However, for most use cases, the built-in Object.assign() method is a reliable and efficient choice.