const firstObject = { moreData: 'foo bar', sampleData: 'Hello world' }
const finalObject = {
firstObject,
};
const firstObject = { moreData: 'foo bar', sampleData: 'Hello world' }
const finalObject = Object.assign({}, firstObject);
--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 | 95068712.0 Ops/sec |
Using Object.assign | 41193700.0 Ops/sec |
The benchmark compares the performance of two different methods for creating a new object in JavaScript: the spread operator (...
) and the Object.assign()
method. The outcomes are measured by the number of executions per second for each approach within a controlled environment.
Using the Spread Operator:
const firstObject = { moreData: 'foo bar', sampleData: 'Hello world' };
const finalObject = { ...firstObject };
Using Object.assign
:
const firstObject = { moreData: 'foo bar', sampleData: 'Hello world' };
const finalObject = Object.assign({}, firstObject);
Object.assign()
method resulted in around 41,193,700 executions per second.Pros:
Cons:
Pros:
Cons:
Object.assign()
performs a shallow copy, so if you're working with nested objects, it can lead to unintended references.When selecting between these two methods, developers should consider the target audience for their applications (browser compatibility) and their team's familiarity with modern JavaScript syntax. Performance is another key factor—in this benchmark, the spread operator exhibited significantly better performance than Object.assign()
, which is a critical observation when developing performance-sensitive applications.
Array.prototype.concat
and Spread Method for Arrays:
While not relevant to object merging, for array operations, the spread operator can also be used in conjunction with array literals, offering similar benefits of readability and performance.
Using Libraries:
There are libraries, such as lodash's _.merge()
or _.assign()
, that can handle deep copies and provide additional functionality for dealing with edge cases. However, using such libraries can introduce overhead and may not be necessary for simple use cases.
When evaluating these options, it’s essential to weigh the trade-offs of performance, code readability, and compatibility to choose the right solution for your application's needs.