var array = Array.from({ length: 100 }).map((val, i) => i);
var newArray = array.splice(0, 0, 99);
var newArray = [99, array];
var newArray = array.unshift(99);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Splice | |
Spread | |
Unshift |
Test name | Executions per second |
---|---|
Splice | 22203.1 Ops/sec |
Spread | 248.2 Ops/sec |
Unshift | 22140.7 Ops/sec |
The provided JSON represents a JavaScript benchmark test case on MeasureThat.net. The test measures the performance of three different approaches to insert an element at the beginning of an array: splice
, spread
, and unshift
. Here's a breakdown of each approach:
array.splice(0, 0, 99)
creates a new array by copying the elements from the original array (excluding the first one) and then adds a new element at the beginning. This method is slower than the others because it involves creating a new array.[99, ...array]
uses the spread operator to create a new array with the new element inserted at the beginning. This method is faster than splice
but still slower than unshift
.array.unshift(99)
modifies the original array by adding an element at the beginning. This method is the fastest because it only requires updating the reference of the first element in the array.Pros and Cons:
Splice
:Spread
:splice
.Unshift
:Other Considerations:
If you need to insert an element at any position in the array, not just at the beginning, splice
is still the best option. However, if performance is critical and you're sure that insertion will only happen at the beginning, unshift
might be a better choice.
The spread operator was introduced in ECMAScript 2015 (ES6) and has since become a standard feature in modern browsers. While it's generally faster than splice
, its support can vary across older browser versions.
Library:
None. This test case doesn't rely on any external libraries.
Special JS Feature/Syntax:
The spread operator (...
) is the only special JavaScript feature used in this benchmark. It was introduced in ECMAScript 2015 (ES6) and allows you to create new arrays by spreading elements from an existing array.
In summary, unshift
is generally the fastest approach for inserting an element at the beginning of an array, while spread
offers a modern alternative that's faster than splice
.