const obj = { one: 'one' };
const res = Object.assign(obj, { toString: function() { return this.one; }});
const res = {obj, toString: function() { return this.one; }};
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign | |
Destructuring |
Test name | Executions per second |
---|---|
Object.assign | 21209232.0 Ops/sec |
Destructuring | 13726364.0 Ops/sec |
The benchmark titled "Object.assign vs destructuring again" aims to compare two JavaScript approaches for merging objects and adding new properties: using Object.assign()
and the spread syntax (...
).
Object.assign
const res = Object.assign(obj, { toString: function() { return this.one; }});
Object.assign()
is a built-in method that copies the values of all enumerable own properties from one or more source objects to a target object. In this case, it takes an existing object obj
and adds a new property toString
to it, which is a function that returns the value of this.one
.Destructuring (with spread)
const res = {...obj, toString: function() { return this.one; }};
...
) allows an iterable (like an object) to be expanded in places where zero or more elements are expected. This syntax creates a new object, incorporating all properties from obj
and adding a new toString
function.Pros:
Cons:
obj
directly).Pros:
Cons:
Object.assign()
in specific cases, as it creates a new object rather than modifying an existing one.Object.assign
resulted in 21,209,232 executions per second, while the destructuring approach had 13,726,364 executions per second in Firefox. This indicates that, at least in this context and environment, Object.assign
was significantly faster.Other alternatives for merging or combining objects in JavaScript include:
Object.entries()
/ Object.fromEntries()
: It can be used to merge key-value pairs with more control, but involves more steps._.merge()
: A utility library that can deeply merge objects but may introduce additional overhead.This benchmark provides a practical insight into the performance trade-offs between two common methodologies for object merging in JavaScript.