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);
const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const field = 'moreData'
firstObject[secondObject[field]] = secondObject
const ob = firstObject
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign | |
property |
Test name | Executions per second |
---|---|
Using the spread operator | 24757724.0 Ops/sec |
Using Object.assign | 6525981.0 Ops/sec |
property | 714438656.0 Ops/sec |
Benchmark Overview
The MeasureThat.net benchmark tests the performance of three different approaches to merge objects in JavaScript:
...
)Object.assign()
firstObject[secondObject[field]] = secondObject
)Spread Operator (...
)
The spread operator is a new syntax introduced in ECMAScript 2018 (ES8). It allows you to expand an object into multiple arguments, making it easier to merge objects.
const finalObject = { ...firstObject, ...secondObject };
Pros:
Cons:
Object.assign()
Object.assign()
is a built-in method that allows you to merge multiple objects into one.
const finalObject = Object.assign(firstObject, secondObject);
Pros:
Cons:
Assigning Properties Dynamically
This approach uses bracket notation to assign properties dynamically.
firstObject[secondObject[field]] = secondObject;
const ob = firstObject;
Pros:
Cons:
Object.assign()
Library: None
There are no libraries involved in this benchmark.
Special JavaScript Features/Syntax: ES8 Spread Operator
The benchmark uses the ES8 spread operator feature, which is a relatively new addition to the JavaScript standard. This feature allows for more concise object merging and has become widely adopted in modern JavaScript development.
Alternative Approaches
Other approaches to merge objects include:
for...in
loops to iterate over object properties_.merge()
)However, the spread operator and Object.assign()
methods are the most commonly used and efficient ways to merge objects in modern JavaScript development.