function assign(a, b) {
for (let i in b) a[i] = b[i];
return (a);
}
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 };
var params = { b:"hello", c: true, d:7 };
var other = assign({ a: 2 }, params);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign | |
spread operator | |
custom assign |
Test name | Executions per second |
---|---|
Object.assign | 5348803.0 Ops/sec |
spread operator | 13378395.0 Ops/sec |
custom assign | 6719630.5 Ops/sec |
Let's break down the benchmark and explain what is being tested, compared, and considered.
Benchmark Overview
The benchmark measures the performance of three different approaches to merge two objects: Object.assign()
, spread operator (...
), and a custom assign()
function. The test case creates an object with properties b
, c
, and d
, and then merges it with another object using each approach.
Comparison
Here's what is being compared:
Object.assign()
: This method takes two or more objects as arguments and returns a new object containing all the enumerable own properties of those objects....
): This operator creates a new object with the same keys as another object, and then copies the values from the original object into the new object.assign()
function: This is a custom implementation that merges two objects using a loop.Pros and Cons
Here are some pros and cons of each approach:
Object.assign()
:...
):assign()
function:Library Usage
None of the three approaches use any external libraries or dependencies.
Special JS Features
The benchmark uses the spread operator (...
), which is a new feature introduced in ECMAScript 2018. The custom assign()
function also uses JavaScript's built-in for...in
loop, but does not rely on any special features beyond that.
Other Considerations
When choosing an approach, consider the following factors:
assign()
function are generally faster than Object.assign()
.Object.assign()
instead.Object.assign()
may be more verbose.Alternatives
If you're looking for alternatives, consider:
assignIn()
function, which provides a fast and efficient way to merge objects.merge()
function from the lodash
library, which also offers performance benefits over Object.assign()
.reduce()
or forEach()
, but this may not be as efficient or readable as the other options.Keep in mind that these alternatives are often more complex and harder to read than the original approaches, so use them with caution.