var array = Array.from(Array(1000).keys())
array.unshift(0);
array = array.concat([0])
array = [0, array]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Unshift | |
Concat | |
Spread |
Test name | Executions per second |
---|---|
Unshift | 26023.9 Ops/sec |
Concat | 1231.2 Ops/sec |
Spread | 299.7 Ops/sec |
Let's break down what's being tested in this JavaScript microbenchmark on MeasureThat.net.
Benchmark Definition JSON
The benchmark definition provides the base script that will be executed to test the performance of different array manipulation techniques. In this case, the script initializes an array with 1000 elements using Array.from(Array(1000).keys())
.
Options being compared
Three options are being compared:
...
) to create a new array from the elements of the original array, starting from the specified position.Pros and Cons of each approach
Library usage
None of the options explicitly use any libraries or external dependencies. However, it's worth noting that some modern JavaScript implementations (e.g., V8) have built-in optimizations and micro-optimizations that can affect performance.
Special JS feature or syntax
The spread operator (...
) is a relatively recent addition to JavaScript, introduced in ECMAScript 2015. It allows for creating new arrays by spreading elements from an existing array. This syntax is not supported in older browsers or environments that don't have the latest ECMAScript standard.
Alternative approaches
Other alternatives for modifying an array include:
Array.prototype.splice()
to insert or remove elements at a specific position.Array.from()
and then modifying it (e.g., new Array(array.length).fill(0).splice(0, 1)
).Keep in mind that the choice of approach depends on the specific requirements and constraints of your project. MeasureThat.net provides a useful benchmarking platform to compare performance across different options.