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 | 20588288.0 Ops/sec |
Using Object.assign | 4712887.5 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
Benchmark Overview
The MeasureThat.net benchmark compares the performance of two ways to merge objects in JavaScript: using the spread operator (...
) and Object.assign()
. The benchmark is designed to measure which approach is faster, but it also provides information about the underlying browser, device platform, operating system, and execution frequency.
Benchmark Definitions
The benchmark definition consists of two test cases:
...
) to merge two objects: firstObject
and secondObject
. The resulting merged object is stored in the finalObject
.const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = {
...firstObject,
...secondObject
}
Object.assign()
method to merge two objects: firstObject
and secondObject
. The resulting merged object is stored in the finalObject
.const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = Object.assign({}, firstObject, secondObject)
Comparison of Options
The benchmark compares the performance of two approaches:
...
) to create a new object with the properties from firstObject
and secondObject
.{}
) and merges the properties from two or more sources.Pros and Cons
Here are some pros and cons of each approach:
Library Usage
Neither of these approaches uses a specific library. They are built-in features of the JavaScript language.
Special JS Features/Syntax
There is no special JavaScript feature or syntax used in this benchmark. Both test cases use only standard JavaScript syntax.
Other Alternatives
If you need to merge objects, there are other alternatives:
reduce()
to merge two objects.const finalObject = firstObject.reduce((acc, key) => ({ ...acc, [key]: acc[key] }), {})
I hope this explanation helps!