const SIZE = 1_000_000;
const original = Array.from({length: SIZE}, (_, i) => i);
const copy = [original];
const copy = original.slice();
const copy = Array.from(original);
const copy = original.map((x) => x);
const copy = [];
for (let i = 0; i < original.length; i++) {
copy[i] = original[i];
}
const copy = [];
let i = 0;
while (i < original.length) {
copy[i] = original[i];
i++;
}
const copy = structuredClone(original);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread | |
slice | |
Array.from | |
map | |
for | |
while | |
structuredClone |
Test name | Executions per second |
---|---|
spread | 132.9 Ops/sec |
slice | 836.4 Ops/sec |
Array.from | 129.0 Ops/sec |
map | 132.2 Ops/sec |
for | 189.5 Ops/sec |
while | 187.7 Ops/sec |
structuredClone | 28.8 Ops/sec |
The benchmark on MeasureThat.net titled "array clone variants" tests various methods for creating a shallow copy (or clone) of an array in JavaScript. It evaluates the performance of several techniques used for this task, measured in "executions per second," which provides a comparative view of how efficiently each method performs when cloning an array of 1,000,000 integers.
Spread Operator ([...]
):
const copy = [...original];
Slice Method (slice()
):
const copy = original.slice();
slice()
method is a classic and established method for shallow copying arrays. It's compatible with older browsers.Array.from Method (Array.from()
):
const copy = Array.from(original);
slice
or the spread operator, especially for large arrays.Map Method (map()
):
const copy = original.map((x) => x);
For Loop:
const copy = [];
for (let i = 0; i < original.length; i++) {
copy[i] = original[i];
}
While Loop:
const copy = [];
let i = 0;
while (i < original.length) {
copy[i] = original[i];
i++;
}
Structured Clone:
const copy = structuredClone(original);
Based on the execution results, we see that the slice method is the fastest for this specific case, followed by the for loop and while loop. Meanwhile, the structuredClone method exhibited significantly lower performance, making it the least favorable choice for shallow copies. The spread operator, Array.from, and map show relatively comparable performance, albeit slower than the classic methods.
In addition to the methods tested, there are alternative approaches to cloning arrays, like using libraries. Libraries like lodash offer a deep clone method (_.cloneDeep
), which can be beneficial if the data structure is complex.
When choosing a method, consider not only performance metrics but also code readability, maintainability, the target environment (compatibility with older browsers), and the complexity of the data you're working with (shallow vs. deep cloning). The optimal choice may vary based on specific project needs and constraints.