var params = { b:"hello", c: true, d:7 };
var other = Object.assign({ a: 2 }, params);
var params = { b:"hello", c: true, d:7 };
var other = { a: 2, params };
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign | |
spread operator |
Test name | Executions per second |
---|---|
Object.assign | 2753616.0 Ops/sec |
spread operator | 1619456.6 Ops/sec |
Let's dive into the details of this benchmark.
What is being tested?
The benchmark is comparing two ways to merge objects in JavaScript:
{ ...obj }
) that creates a shallow copy of an object, where obj
is the source object.What options are compared?
In this benchmark, two test cases are run:
Object.assign()
method to merge a predefined object (params
) with another object containing only one property (a: 2
). The resulting merged object is assigned to the variable other
.var params = { b:"hello", c: true, d:7 };
var other = Object.assign({ a: 2 }, params);
{ ...params }
) to create a new object that includes all properties from the params
object, along with an additional property (a: 2
). The resulting merged object is assigned to the variable other
.var params = { b:"hello", c: true, d:7 };
var other = { a: 2, ...params };
Pros and Cons of each approach
Both methods achieve the same result (merging objects), but with some differences:
Object.assign
due to the overhead of creating a new object.Other considerations
When choosing between these methods, consider:
Object.assign
.Object.assign
might be a better choice due to its faster execution time.Libraries and special JS features
In this benchmark, no external libraries are used. The test cases only utilize built-in JavaScript methods and syntax (specifically, the spread operator).
Alternative approaches
Other ways to merge objects in JavaScript include:
Object.assign
as a starting point.These alternatives might offer additional features, such as handling nested objects or merging arrays, but are not used in this specific benchmark.