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 finalObject = Object.assign({}, firstObject, secondObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign | |
Using Object.assign no mutation |
Test name | Executions per second |
---|---|
Using the spread operator | 38545340.0 Ops/sec |
Using Object.assign | 10769090.0 Ops/sec |
Using Object.assign no mutation | 8661344.0 Ops/sec |
Let's break down what is tested on the provided JSON and explain the different approaches compared.
Benchmark Overview
The benchmark measures the performance of two ways to merge objects in JavaScript: using the spread operator (...
) and Object.assign()
. The tests are designed to preserve previous data when merging two objects.
Options Compared
...
):{ ...firstObject, ...secondObject }
to create a new object with merged properties from both firstObject
and secondObject
.Object.assign()
:Object.assign()
method to merge two objects into one: const finalObject = Object.assign(firstObject, secondObject);
.Object.assign()
without mutation (Object.assign({}, firstObject, secondObject)
):Object.assign()
to merge two objects into a new object: const finalObject = Object.assign({}, firstObject, secondObject);
.Library/Utility Used
None, as this is a built-in JavaScript feature (...
spread operator) or a standard method (Object.assign()
).
Special JS Features/Syntax
The benchmark uses the new spread operator syntax ({ ...firstObject, ...secondObject }
) which was introduced in ECMAScript 2018 (ES2018). This syntax allows for more concise and expressive object merging.
Other Considerations
Object.assign()
.Alternatives
If you're not interested in using the latest JavaScript features or want more control over the merging process, alternative methods include:
Object.assign()
with nested objects support (e.g., using Object.assign()
recursively).merge
function to handle complex object merges.However, these alternatives may come at the cost of increased code complexity or performance overhead.