const a = { x: 'xxx', y: 1, z: null }
const b = { z: 1, u: 'uuu', v: null }
Object.assign(a, b);
const a = { x: 'xxx', y: 1, z: null }
const b = { z: 1, u: 'uuu', v: null }
for (let prop in b)
a[prop] = b[prop];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign | |
for in loop |
Test name | Executions per second |
---|---|
Object.assign | 6631004.0 Ops/sec |
for in loop | 6928677.5 Ops/sec |
Let's break down the JavaScript microbenchmark on MeasureThat.net.
Benchmark Definition
The benchmark tests two approaches to merge two objects in JavaScript: Object.assign()
and a traditional for-in
loop.
Options being compared
Two options are compared:
Pros and Cons
Here are the pros and cons of each approach:
for-in
loop due to the overhead of function calls.Object.assign()
due to reduced function call overhead.Library
The benchmark does not use any external libraries.
Special JS features or syntax
There are no special JavaScript features or syntaxes mentioned in the benchmark definition. However, it's worth noting that Object.assign()
has been around since ECMAScript 2015 (ES6), while traditional for-in
loops have been available since early versions of JavaScript.
Other alternatives
If you want to explore alternative approaches to merging objects, here are a few options:
...
): This is a newer approach that's gaining popularity, allowing you to merge two objects using the syntax const result = { ...a, ...b };
.Keep in mind that the choice of approach ultimately depends on your specific use case, performance requirements, and personal preference.