var obj1 = { a: 'a' };
const obj2 = {obj1, b: 'b'};
const obj2 = Object.assign(obj1, {b: 'b'});
const obj2 = Object.assign({}, obj1, {b: 'b'});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread | |
Object.assign (modify) | |
Object.assign (new) |
Test name | Executions per second |
---|---|
Spread | 6091695.5 Ops/sec |
Object.assign (modify) | 3308585.5 Ops/sec |
Object.assign (new) | 2885490.0 Ops/sec |
Let's dive into the explanation of the provided benchmark.
What is tested?
The provided JSON represents a JavaScript microbenchmark that compares three different approaches to merge two objects:
{...obj1, b: 'b'}
) to create a new object by copying obj1
and adding a new property b
.Object.assign(obj1, {b: 'b'})
to merge obj1
with an object containing the new property b
.Object.assign({}, obj1, {b: 'b'})
to create a new object by merging obj1
and an object containing the new property b
.Options comparison
The three approaches have different pros and cons:
obj1
by adding a new property b
. While it's straightforward, it can be seen as less intuitive and may have unexpected side effects if used in other parts of the codebase.obj1
with an empty object and then adding the new property b
. It is more explicit but may be slightly slower due to the extra object creation.Library usage
The benchmark uses the built-in Object.assign()
method, which is a part of the ECMAScript standard. Its purpose is to copy properties from one or more source objects to a target object.
Special JavaScript features
There are no special JavaScript features or syntax used in this benchmark.
Other alternatives
For merging two objects, other approaches exist:
concat()
method: var obj2 = obj1.concat({b: 'b'})
var obj2 = {}; for (var key in obj1) { obj2[key] = obj1[key]; } obj2.b = 'b';
Object.create()
: var obj2 = Object.create(obj1); obj2.b = 'b';
Keep in mind that these alternatives may have different performance characteristics and readability compared to the three approaches tested in this benchmark.
I hope this explanation helps software engineers understand the provided benchmark!