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 = {}
for (let key in firstObject) {
finalObject[key] = firstObject[key];
}
for (let key in secondObject) {
finalObject[key] = secondObject[key];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign | |
Using For-In loop |
Test name | Executions per second |
---|---|
Using the spread operator | 6498894.5 Ops/sec |
Using Object.assign | 9259487.0 Ops/sec |
Using For-In loop | 21993606.0 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Description The benchmark is designed to measure the performance of three different approaches for merging objects without mutating them:
...
): This syntax allows you to create a new object with all the properties from an existing object.Object.assign()
: This method creates a new object and copies all properties from one or more source objects into it.Options Comparison
Object.assign()
is often slower than the spread operator because it involves creating a new array of properties to be assigned, which can lead to additional overhead.Pros and Cons
Object.assign()
:Library/Functionality
None mentioned in the benchmark definition. However, Object.assign()
is a built-in function in modern JavaScript engines.
Special JS Feature/Syntax
The spread operator (...
) is an ES6+ feature that allows for more concise object merging. It's widely supported across modern browsers and environments.
Alternatives Other approaches for merging objects without mutating them could include:
merge()
function from a library like Lodash.Object.fromEntries()
method (introduced in ES2020).These alternatives might offer different performance characteristics, trade-offs between code readability and conciseness, or additional features like handling nested objects or arrays.