var array = [];
for (let m = 0; m < 40; m++) {
array.push(m);
}
let clone = array.slice();
let clone = [array];
let clone = [];
clone.push(array);
let clone = [];
for (let i = 0; i < array.length; i++) {
clone.push(array[i]);
}
let clone = [].concat(array);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using array slice | |
Using array spread | |
Using array push and spread | |
Using for loop and push | |
Using array concat |
Test name | Executions per second |
---|---|
Using array slice | 14033803.0 Ops/sec |
Using array spread | 2267991.0 Ops/sec |
Using array push and spread | 3965722.5 Ops/sec |
Using for loop and push | 4719972.0 Ops/sec |
Using array concat | 3480998.5 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition
The benchmark is designed to measure the performance of cloning an array with 40 items. The script preparation code creates an empty array and populates it with numbers from 0 to 39 using a for
loop. The resulting array is then used as input for each test case.
Test Cases
There are four test cases, each attempting to clone the array using a different approach:
let clone = array.slice();
let clone = [...array];
let clone = [];\r\nclone.push(...array);
let clone = [];\r\nfor (let i = 0; i < array.length; i++) {\r\n clone.push(array[i]);\r\n}
let clone = [].concat(array);
Each test case is executed multiple times, and the results are stored in a raw UA string, which represents the user agent (UA) of the browser running the benchmark.
Options Compared
The different approaches for cloning the array can be summarized as follows:
Pros and Cons
Here's a brief analysis of the pros and cons of each approach:
Library Considerations
The test cases do not explicitly mention any libraries being used beyond JavaScript's built-in features. However, if we consider external libraries or frameworks that might be used in real-world scenarios, some examples include:
slice()
and concat()
....
): Introduced in ECMAScript 2015 (ES6), it allows for creating new arrays from existing ones.Special JS Features or Syntax
The benchmark does not explicitly mention any special JavaScript features or syntax beyond those introduced by ES6. However, if we consider more advanced concepts like generators, async/await, or typed arrays, they might be relevant in a real-world scenario.
Now that we've broken down the provided information, let's discuss other alternatives for benchmarking array cloning:
Keep in mind that this is just a brief analysis, and there are many more nuances to consider when benchmarking specific use cases.