var vertices = [
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]
var myCopy = null;
myCopy = JSON.parse(JSON.stringify(vertices));
myCopy = vertices.map(row => row.slice());
myCopy = vertices.map(row => Array.from(row))
myCopy = vertices.map(row => [row])
myCopy = structuredClone(vertices)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.stringify | |
slice | |
Array from | |
Spread | |
structuredClone |
Test name | Executions per second |
---|---|
JSON.stringify | 1476443.8 Ops/sec |
slice | 6490270.0 Ops/sec |
Array from | 4155363.8 Ops/sec |
Spread | 6255413.5 Ops/sec |
structuredClone | 768376.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, along with their pros and cons.
Benchmark Overview
The benchmark measures the performance of different methods to create a shallow copy of an array-like object (in this case, a 3D vertex array). The goal is to determine which method is the most efficient.
Methods Being Tested
JSON.stringify
followed by JSON.parse
Array.prototype.slice
Array.from
...
)structuredClone
Analysis of Each Method
JSON.stringify
followed by JSON.parse
Implementation: myCopy = JSON.parse(JSON.stringify(vertices));
Array.prototype.slice
Implementation: myCopy = vertices.map(row => row.slice());
Array.from
( Introduced in ES6+ )Implementation: myCopy = vertices.map(row => Array.from(row));
...
)Implementation: myCopy = [...vertices];
structuredClone
( Introduced in ES2022 )Implementation: myCopy = structuredClone(vertices);
Library Used
None explicitly mentioned, but all methods rely on underlying browser implementations of JavaScript features. The main library involved is the Web API (Web Application Programming Interface) and the ECMAScript specification.
Other Considerations
Alternatives
For this specific use case (shallow copy of an array-like object), other alternatives might include:
Array.prototype.map
with a callback functioncloneDeep
Keep in mind that each alternative will have its own pros and cons, depending on the specific requirements of your project.