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 | 3700487.2 Ops/sec |
Using Object.assign | 5547838.5 Ops/sec |
Let's break down what's being tested in this benchmark.
What is being tested?
The benchmark compares the performance of two approaches to merge objects:
...
): The ...
operator is used to spread the properties of an object into a new object. In the provided code, firstObject
and secondObject
are merged into finalObject
using this approach.Object.assign()
: This method returns a new object with the properties of two or more source objects.Options compared
The benchmark tests these two options for merging objects, which is a fundamental operation in JavaScript programming.
Pros and Cons:
...
):Object.assign()
:Object.assign({}, firstObject, secondObject)
to create a new object with specific properties).Library and special JS features
Object
: The Object
constructor is used in the benchmark to create empty objects (const finalObject = Object.assign({}, firstObject, secondObject);
)....
): This feature was introduced in ECMAScript 2018 (ES10) and allows spreading iterable values into new objects.Object.assign()
: This method has been part of the JavaScript language since its inception.Other alternatives
While not explicitly mentioned in this benchmark, other ways to merge objects in JavaScript include:
Object.create()
method: const finalObject = Object.create(firstObject).constructor = secondObject.constructor;
_.merge()
): const finalObject = _.merge({}, firstObject, secondObject);
Note that these alternatives may have different performance characteristics or trade-offs in terms of readability and conciseness.