const firstObject = { a: 1, b: 2, c: 3, d: 4 }
const finalObject = { firstObject };
const firstObject = { a: 1, b: 2, c: 3, d: 4 }
const finalObject = Object.assign({}, firstObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign |
Test name | Executions per second |
---|---|
Using the spread operator | 19474884.0 Ops/sec |
Using Object.assign | 45554700.0 Ops/sec |
The benchmark defined in the provided JSON evaluates the performance of two different JavaScript approaches for cloning an object: using the spread operator and using Object.assign
. The benchmark specifically compares the execution speed of these two methods under the same conditions.
Using the spread operator (...
):
const firstObject = { a: 1, b: 2, c: 3, d: 4 };
const finalObject = { ...firstObject };
Using Object.assign
:
const firstObject = { a: 1, b: 2, c: 3, d: 4 };
const finalObject = Object.assign({}, firstObject);
...
):Object.assign
:Object.assign
.Object.assign
would be a more compatible choice. However, most modern projects focus on ES6 features._.cloneDeep
for deep cloning, which can handle nested objects. However, this comes with increased overhead and should be used when necessary.Overall, the result of the benchmark indicates that the spread operator is not only more elegant but also a faster choice for cloning objects in JavaScript in the tested environment (Chrome 131). This performance difference is significant to consider when deciding which method to use in development.