const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = {
secondObject,
__key: "a key",
__src: "a src",
};
const firstObject = { __key: "a key", __src: "a src", }
const secondObject = { moreData: 'foo bar' }
const finalObject = Object.assign(firstObject, secondObject);
const firstObject = { __key: "a key",
__src: "a src", }
const secondObject = { moreData: 'foo bar' }
const finalObject = {
secondObject,
firstObject
};
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator with constant inside | |
Using Object.assign | |
Using the spread operator |
Test name | Executions per second |
---|---|
Using the spread operator with constant inside | 82493128.0 Ops/sec |
Using Object.assign | 9045195.0 Ops/sec |
Using the spread operator | 25963040.0 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Overview
The benchmark compares the performance of three different approaches to merge objects in JavaScript: using the spread operator (...
), Object.assign()
, and simply concatenating object literals.
Options Compared
...
) to create a new object with all the properties from secondObject
. The spread operator is used to copy all own enumerable properties (key-value pairs) of secondObject
into a new object.Object.assign()
method, which returns a new object containing all own enumerable properties (key-value pairs) from both passed objects.+
operator, creating a new object with all properties from both objects.Pros and Cons
Object.assign()
with a function as the target object).Library/Function Used
None. This benchmark does not rely on any external libraries or functions beyond the standard JavaScript API.
Special JS Features/Syntax
The spread operator (...
) is a modern JavaScript feature introduced in ECMAScript 2015 (ES6). It allows for concise syntax to create new objects with properties from an existing object.
Alternative Approaches
Other approaches to merge objects in JavaScript include:
merge()
method of some libraries, such as Lodash.Keep in mind that each approach has its pros and cons, and the best choice depends on the specific use case, performance requirements, and personal preference.