var arr = [1,2,3]
var a = arr.unshift(99)
var a = [99, arr]
var a = arr.concat([99])
var a = arr.splice(0, 0, 99)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.unshift | |
spread operator | |
Array.prototype.concat | |
Array.prototype.splice |
Test name | Executions per second |
---|---|
Array.prototype.unshift | 23175.0 Ops/sec |
spread operator | 117.2 Ops/sec |
Array.prototype.concat | 534.5 Ops/sec |
Array.prototype.splice | 1381.9 Ops/sec |
I'll explain what's being tested in the provided benchmark.
The test cases are designed to measure the performance of three different ways to add an element to the beginning of an array:
Array.prototype.unshift()
: This method adds one or more elements to the beginning of an array and returns the new length of the array....
): This is a shorthand way to create a new array by spreading the elements of an existing array.Array.prototype.concat()
(in combination with array slicing): This method concatenates two or more arrays and returns a new array.The test cases compare these three approaches in terms of execution speed.
Now, let's discuss the pros and cons of each approach:
1. Array.prototype.unshift()
Pros:
Cons:
2. The spread operator (...
)
Pros:
Cons:
3. Array.prototype.concat()
(in combination with array slicing)
Pros:
Array.prototype.unshift()
is not available or supportedCons:
Now, let's take a look at some special JavaScript features used in these test cases:
...arr
): Used with the spread operator to create a new array by spreading elements from an existing array.Finally, let's consider some alternatives for measuring the performance of these methods:
However, for most purposes, the provided JSON and test cases should be sufficient to compare the performance of these three approaches.