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 | 1561961.5 Ops/sec |
Using Object.assign | 3542588.0 Ops/sec |
What is being tested?
MeasureThat.net is testing the performance of two approaches to merge objects in JavaScript:
...
): This syntax allows you to expand an object's properties into another object.The benchmark compares the performance of these two approaches when merging two objects without mutating the original objects.
Options being compared
...
) for object mergingObject.assign()
for object mergingPros and Cons of each approach:
Using the Spread Operator (...
)
Pros:
Cons:
Using Object.assign()
Pros:
Cons:
Other considerations
Object.assign()
has been a built-in method of the global Object
since ECMAScript 5 (2009), so it doesn't require any external libraries.Special JS feature or syntax
None are explicitly mentioned in this benchmark. However, the spread operator (...
) was introduced in ECMAScript 2018 and might not work correctly in older JavaScript engines.
Other alternatives
If you prefer a different approach to object merging, here are some alternative methods:
Object.assign()
or other means.merge()
function or a custom implementation.Keep in mind that these alternatives might have different performance characteristics compared to the spread operator and Object.assign()
.