const firstObject = {
name: 'Alice',
age: 25,
contact: {
email: 'alice@example.com',
phone: '123-456-7890',
},
preferences: {
language: 'English',
timezone: 'UTC',
},
};
const secondObject = {
job: 'Software Engineer',
skills: ['JavaScript', 'React', 'Node.js'],
contact: {
email: 'alice.work@example.com',
},
preferences: {
theme: 'dark mode',
},
};
const finalObject = {
firstObject,
secondObject
};
const firstObject = {
name: 'Alice',
age: 25,
contact: {
email: 'alice@example.com',
phone: '123-456-7890',
},
preferences: {
language: 'English',
timezone: 'UTC',
},
};
const secondObject = {
job: 'Software Engineer',
skills: ['JavaScript', 'React', 'Node.js'],
contact: {
email: 'alice.work@example.com',
},
preferences: {
theme: 'dark mode',
},
};
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 | 15247128.0 Ops/sec |
Using Object.assign | 19903526.0 Ops/sec |
The provided benchmark tests the performance of two different methods for merging JavaScript objects: the spread operator (...
) and the Object.assign()
method. Both techniques are commonly used to combine properties from multiple objects into a single object, which can be a typical requirement in JavaScript programming.
Using the Spread Operator (...
)
const finalObject = {
...firstObject,
...secondObject
};
Object.assign()
in certain scenarios, although in modern JavaScript engines, this is often negligible.Using Object.assign()
const finalObject = Object.assign(firstObject, secondObject);
Object.assign()
.Object.assign()
with the first argument as a new object, you can avoid modifying the original objects. Object.assign()
is also part of ES6 and faces similar support issues.cloneDeep
) would be needed.Lodash or Underscore.js:
JSON methods:
JSON.parse(JSON.stringify(object))
can create a deep copy of an object but isn't suitable for functions, undefined
, or circular references.Manual Merge:
The benchmark clearly indicates higher performance for Object.assign()
in this particular case, but the choice between the spread operator and Object.assign()
can depend on readability, use case, and personal or team preference. Understanding the pros and cons of both methods can guide engineers in selecting the appropriate approach for their specific requirement.