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 };
const copy = {};
Object.assign(copy, voucher)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
window.structuredClone | |
Spread syntax | |
Object assign |
Test name | Executions per second |
---|---|
window.structuredClone | 567692.6 Ops/sec |
Spread syntax | 7433920.0 Ops/sec |
Object assign | 27664068.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark is comparing three different approaches to create a copy of an object in JavaScript:
window.structuredClone(voucher)
{ ...voucher }
(Spread syntax)Object.assign(copy, voucher)
(Object assign)Library and Purpose
structuredClone
is a new JavaScript method introduced in ECMAScript 2020, which allows creating a shallow clone of an object. It's designed to be more efficient and flexible than traditional methods like Object.assign()
or the spread syntax.
Options Compared
The benchmark compares three options:
window.structuredClone(voucher)
: This method creates a shallow clone of the voucher
object using the new structuredClone
function....
) to create a shallow copy of the voucher
object.voucher
object by assigning its properties to a new object using Object.assign()
.Pros and Cons
Here's a brief summary of each approach:
window.structuredClone(voucher)
structuredClone
for large objectsstructuredClone
for large objectsOther Considerations
When choosing an approach, consider the specific requirements of your project:
structuredClone
might be a better choice.Object.assign()
.structuredClone
is likely a better option.Alternatives
Other alternatives for creating object copies include:
Object.assign()
to create a new object, then converts it to an array using slice.call()
.Keep in mind that these alternatives may have different trade-offs and performance characteristics compared to the approaches tested in this benchmark.