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 | 1130273.8 Ops/sec |
Using Object.assign | 2993334.0 Ops/sec |
What is being tested?
The provided benchmark measures the performance difference between using the JavaScript spread operator (...
) and Object.assign
to merge two objects into a single object.
Options compared:
Two approaches are being compared:
...
) to create a new object by copying properties from the first object (firstObject
) and then merging them with properties from the second object (secondObject
). The syntax is:const finalObject = { ...firstObject, ...secondObject };
Object.assign
: This method uses the Object.assign
method to merge two objects into a single object. The syntax is:const finalObject = Object.assign({}, firstObject, secondObject);
Pros and Cons of each approach:
Object.assign
:Object
prototype.Map
and Set
.Library:
In this benchmark, no libraries are being used beyond the built-in JavaScript methods (Object.assign
).
Special JS feature or syntax:
The spread operator is a relatively recent feature introduced in ECMAScript 2018. It's available in most modern browsers, but not all older browsers support it.
Other alternatives:
Alternative approaches to merge two objects include:
Object.create()
constructor, which is then assigned properties.const finalObject = Object.create(null);
finalObject.sampleData = 'Hello world';
finalObject.moreData = 'foo bar';
const finalObject = {};
for (const prop in firstObject) {
if (firstObject.hasOwnProperty(prop)) {
finalObject[prop] = firstObject[prop];
}
}
finalObject.moreData = secondObject.moreData;
These alternatives may have different performance characteristics and are not as concise or readable as the spread operator or Object.assign
.