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 = window.structuredClone(voucher);
const copy = { voucher };
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
window.structuredClone | |
Spread syntax |
Test name | Executions per second |
---|---|
window.structuredClone | 433502.5 Ops/sec |
Spread syntax | 34911496.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark compares two approaches to create a copy of an object in JavaScript: structuredClone
and spread syntax ({ ...voucher }
). The goal is to determine which approach is faster, more efficient, or both.
Options Compared
There are two options being compared:
window.structuredClone(voucher)
: This method uses the structuredClone
function, introduced in JavaScript 2020, to create a deep copy of the object voucher
. The structuredClone
function is designed to produce an exact clone of the original object, including its internal properties and references.{ ...voucher }
): This method uses the spread operator (...
) to create a shallow copy of the object voucher
. The resulting object will have all the same properties as the original object, but any nested objects or arrays may not be copied recursively.Pros and Cons
structuredClone(voucher)
:{ ...voucher }
):structuredClone
because it only creates a shallow copy, which requires less work.Library/Feature
There is no library being used in this benchmark. However, structuredClone
is a built-in JavaScript feature introduced in 2020, making it a part of the language itself.
Special JS Feature/Syntax
The benchmark uses the structuredClone
function, which was introduced as a proposed feature in ECMAScript 2020 and later adopted as a standard. The spread syntax ({ ...voucher }
) is also a built-in JavaScript feature that has been available since ECMAScript 2015.
Other Alternatives
If you're interested in exploring other approaches to create copies of objects, here are some alternatives:
JSON.parse(JSON.stringify(voucher))
method (shallow copy)cloneDeep()
function (deep copy)Keep in mind that each approach has its own trade-offs and may not be suitable for all use cases.
I hope this explanation helps you understand the benchmark and the options being compared!