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 | 13573774.0 Ops/sec |
Using Object.assign | 10422555.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Goal
The goal of this benchmark is to compare the performance of two ways to merge objects in JavaScript: using the spread operator (...
) and Object.assign()
with an empty object ({}
) as the target.
Test Cases
There are two test cases:
firstObject
and secondObject
, and then uses the spread operator to merge them into a new object, finalObject
. The syntax is: const finalObject = { ...firstObject, ...secondObject }
.Object.assign()
with an empty object as the target to merge them into a new object, finalObject
. The syntax is: const finalObject = Object.assign({}, firstObject, secondObject);
.Library and Special JS Feature
In this benchmark, there are no external libraries used. However, it does utilize a special JavaScript feature introduced in ECMAScript 2018 (ES2018): the rest/spread operator (...
).
The rest/spread operator allows you to create a new object by "spreading" properties from an existing object or array. In this benchmark, it's used to merge objects using the spread operator.
Pros and Cons
Here are some pros and cons of each approach:
Object.assign()
due to the overhead of the spread operator.Object.assign(target, ...)
).Other Alternatives
If you need to merge objects in JavaScript, there are other alternatives:
reduce()
method: You can use the reduce()
method to combine two arrays or objects into a single array or object. For example: const finalObject = Object.values(firstObject).concat(Object.values(secondObject)).reduce((a, b) => ({ ...a, ...b }), {})
.merge()
function that can handle various merging scenarios.const finalObject = { ...firstObject, ...secondObject };
. However, this approach may not be as expressive or readable as using the spread operator or Object.assign()
.