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 = Object.assign({}, firstObject, secondObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign | |
Using Object.assign for new object |
Test name | Executions per second |
---|---|
Using the spread operator | 3138294.8 Ops/sec |
Using Object.assign | 7437840.5 Ops/sec |
Using Object.assign for new object | 6722896.5 Ops/sec |
Overview
The provided JSON represents a JavaScript microbenchmark test case on MeasureThat.net. The benchmark tests the performance of three different approaches for merging two objects in JavaScript: using the spread operator, Object.assign
, and creating a new object with Object.assign
. The test results are compared across various browsers and devices.
Benchmarked Approaches
{...obj1, ...obj2}
to merge two objects, obj1
and obj2
. The spread operator is a shorthand way of creating a new object with properties from multiple sources.Object.assign()
method to merge two objects. It assumes that both inputs are objects and attempts to assign all own enumerable property values of one or more source objects to an existing target object.Object.assign({}, obj1, obj2)
and then assigns the result to the new object.Comparison
The pros and cons of each approach are:
Object.assign()
due to the overhead of creating a new objectnew Object()
Object.assign()
Library and Features
The benchmark does not use any external libraries. However, it does utilize JavaScript features such as:
{...obj1, ...obj2}
)Object.assign()
methodThese features are supported by most modern browsers.
Test Results
The latest test results show that:
Object.assign()
.Object.assign({}, obj1, obj2)
has a similar performance to traditional Object.assign()
.Alternatives
Other alternatives for merging two objects in JavaScript include:
{...obj1, ...obj2}
syntax with Object.create()
(e.g., const finalObj = Object.create(obj1); finalObj[Symbol.for('foo')]= obj2['foo'];
)merge()
functionObject.assign()
to merge the objectsHowever, these alternatives may introduce additional overhead or complexity compared to the traditional approaches tested in this benchmark.