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 | 1767015.0 Ops/sec |
Using Object.assign | 4055925.2 Ops/sec |
This benchmark tests the performance of two methods for combining JavaScript objects: the spread operator (...
) and Object.assign()
.
Let's break down each method:
Using the Spread Operator (...
): This approach involves creating a new object literal and using the spread syntax to include properties from existing objects within it.
const firstObject = { sampleData: 'Hello world' };
const secondObject = { moreData: 'foo bar' };
const finalObject = { ...firstObject, ...secondObject };
Using Object.assign()
: This method takes a target object and one or more source objects, copying properties from the sources into the target.
const firstObject = { sampleData: 'Hello world' };
const secondObject = { moreData: 'foo bar' };
const finalObject = Object.assign({}, firstObject, secondObject);
Pros and Cons:
Spread Operator:
Object.assign()
, especially with a large number of objects.Object.assign()
:
Other Considerations:
Object.assign()
might offer a more noticeable speed advantage.Alternatives:
While Object.assign
and the spread operator are common methods for object merging, you could also consider using libraries like Lodash or Ramda, which provide specialized functions for object manipulation with potentially optimized performance.
Let me know if you have any more questions.