<!--your preparation HTML code goes here-->
var voucher = {
"single": false,
"applyOverTaxes": false,
"discountType": "1",
"value": 100,
"minimumAmount": 0,
"quantity": 1,
"suffixLength": 8,
"code": "IF5R0AFX",
"vertical": [],
"allowedPaymentMethods": [],
"allowedBanks": [],
"types": [],
"partners": [],
"startDate": "2020-10-21T00:00:00.000Z",
"endDate": "2020-10-21T00:00:00.000Z",
"applyed": false
}
const copy = structuredClone(voucher)
const copy = { voucher }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
structuredClone | |
spread |
Test name | Executions per second |
---|---|
structuredClone | 306444.5 Ops/sec |
spread | 34831788.0 Ops/sec |
This benchmark compares the performance of two JavaScript methods for creating a shallow copy of an object: the spread operator ({ ...voucher }
) and the structuredClone
function (structuredClone(voucher)
).
Test Name: structuredClone
const copy = structuredClone(voucher)
structuredClone
is a built-in JavaScript function introduced in the HTML Living Standard and widely in modern JavaScript environments. Its purpose is to create a deep copy of a JavaScript object, handling complex types like nested objects and arrays seamlessly.Test Name: spread
const copy = { ...voucher }
...
) is a feature of ES6 (ECMAScript 2015) that allows an iterable (e.g., an array or object) to be expanded into its elements.structuredClone
for creating copies of simple objects, as it does not have the overhead of deep copying.The benchmark results show a significant difference in performance:
structuredClone
function achieved 306,444.53 executions per second.This indicates that for simple object copying, the spread operator is vastly superior in performance. However, if the object being copied contains nested structures, the structuredClone
method's ability to deep copy those structures becomes invaluable, despite its performance drawbacks.
Shallow vs. Deep Copy: Understanding the distinction between how data is copied (shallow vs. deep) is critical when deciding which method to use. If you only need to copy the top level of an object and there are no nested references of concern, the spread operator is likely preferable due to its speed.
Other Alternatives:
Object.assign({}, voucher)
. It's similar in functionality to the spread operator with slightly different syntax and may have different performance characteristics._.cloneDeep
for deep copying, if you need to deal with complex structures in a more controlled manner. While powerful, using external libraries can influence bundle size and performance.In summary, the choice between using structuredClone
and the spread operator (or alternatives) should carefully consider the nature of the object being copied and the trade-offs between performance and the need for deep vs. shallow copies.