const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const arr1 = [0, arr];
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.unshift(0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new array | |
mutation |
Test name | Executions per second |
---|---|
new array | 15202711.0 Ops/sec |
mutation | 33625660.0 Ops/sec |
Let's break down the provided JSON data and explain what's being tested.
Benchmark Definition
The benchmark is defined by two test cases:
[0, ...arr]
) versus creating an empty array and then pushing elements into it.unshift
method.Options compared
In each test case, the following options are being compared:
[0, ...arr]
)[]
followed by .push(arr)
or .concat(arr)
)unshift
methodPros and Cons
Here are some pros and cons of each approach:
For "new array":
[0, ...arr]
) has the advantage of being more concise and readable. It also avoids creating an intermediate array.Creating an empty array and then pushing elements into it:
For "mutation":
Using the unshift
method can be faster for large arrays because it modifies the existing array in-place without creating a new one.
However, this approach requires modifying the original array, which might not be desirable in all cases.
Creating a new array and then assigning it to a variable:
unshift
because it creates an additional array object.Libraries and special JS features
None of the test cases use any external libraries. The only special JavaScript feature being tested here is the spread operator ([0, ...arr]
) introduced in ECMAScript 2015 (ES6).