var firstObject = {
sampleData: 'Hello world'
}
var secondObject = {
moreData: 'foo bar'
}
var merge = (def, opt) => {
if (!opt) return def
for (const key in def) {
if (!Object.prototype.hasOwnProperty.call(opt, key) || opt[key] === undefined)
opt[key] = def[key]
else if (opt[key] === Object(opt[key]))
opt[key] = merge(def[key], opt[key])
}
return opt
}
const finalObject = {
firstObject,
secondObject
}
const finalObject = Object.assign(firstObject, secondObject)
const finalObject = merge(firstObject, secondObject)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign | |
Using custom merge method (Create a clone object) |
Test name | Executions per second |
---|---|
Using the spread operator | 8640652.0 Ops/sec |
Using Object.assign | 5470456.0 Ops/sec |
Using custom merge method (Create a clone object) | 1495925.0 Ops/sec |
Benchmark Overview
The provided JSON represents a JavaScript microbenchmarking test case on the MeasureThat.net website. The benchmark compares the performance of three different methods to merge two objects: the spread operator, Object.assign
, and a custom merge method.
Options Compared
const finalObject = { ...firstObject, ...secondObject }
to create a new object with merged properties.Object.assign()
method to merge two objects: const finalObject = Object.assign(firstObject, secondObject)
.merge
) that recursively merges two objects.Pros and Cons
Object
global object, which might not be available in some environments.Library/Functions Used
Object.assign()
is a built-in function.Special JS Features/Syntax
None explicitly used in this benchmark.
Benchmark Preparation Code Explanation
The script preparation code defines three objects (firstObject
and secondObject
) with some sample data, followed by the custom merge method implementation:
var firstObject = {
sampleData: 'Hello world'
};
var secondObject = {
moreData: 'foo bar'
};
var merge = (def, opt) => {
// ... (custom merge function implementation)
};
Individual Test Cases
Each test case defines a different benchmark by using the corresponding method to merge firstObject
and secondObject
. The resulting final object is stored in a variable named finalObject
.
const finalObject = { ...firstObject, ...secondObject }
const finalObject = Object.assign(firstObject, secondObject)
const finalObject = merge(firstObject, secondObject)
Latest Benchmark Result Explanation
The benchmark results show the performance metrics for each test case on a Chrome 121 desktop running Linux:
The results suggest that the spread operator is the fastest method, followed by Object.assign
, and then the custom merge method.
Other Alternatives
JSON.parse()
and JSON.stringify()
to serialize the objects before merging them, might also be considered as alternatives.