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 | 2150172.0 Ops/sec |
Using Object.assign | 5243596.5 Ops/sec |
Let's break down what's being tested in this benchmark.
What's being tested?
The benchmark is comparing the performance of two approaches to merge two objects: using the JavaScript spread operator (...
) and using Object.assign()
without mutating the original object.
Options compared
The two options being compared are:
...
syntax to create a new object that includes all properties from both firstObject
and secondObject
.Object.assign()
with an empty object as the target, and then merging the properties of firstObject
and secondObject
into it.Pros and cons
Object.assign()
Library/Dependency
Neither of these approaches relies on a specific library or dependency. However, Object.assign()
is a built-in method in JavaScript that has been available since ECMAScript 2015 (ES6).
Special JS feature/syntax
There are no special JS features or syntax being tested in this benchmark.
Other alternatives
If you want to explore other approaches to merging objects, here are some alternatives:
Object.keys()
and reduce()
methods: You can use Object.keys()
to get an array of property names from both objects, and then use reduce()
to create a new object with merged properties.Here's an example implementation using the Object.keys()
and reduce()
methods:
const firstObject = { sampleData: 'Hello world' };
const secondObject = { moreData: 'foo bar' };
const finalObject = Object.keys(firstObject).reduce((obj, key) => {
obj[key] = firstObject[key];
}, {});
finalObject[Object.keys(secondObject)[0]] = secondObject[Object.keys(secondObject)[0]];
And here's an example implementation using Lodash:
import _ from 'lodash';
const firstObject = { sampleData: 'Hello world' };
const secondObject = { moreData: 'foo bar' };
const finalObject = _.merge({}, firstObject, secondObject);
Note that these alternatives may have different performance characteristics or trade-offs depending on your specific use case.