var array = [1,2,3];
var array2 = [4,5,6];
array.unshift(array2);
array = array.concat(array2)
array = [array, array2]
array.push(array2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
arrayUnshift | |
arrayConcat | |
arraySpread | |
arrayPush |
Test name | Executions per second |
---|---|
arrayUnshift | 16288.0 Ops/sec |
arrayConcat | 489.5 Ops/sec |
arraySpread | 187.9 Ops/sec |
arrayPush | 4542563.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark measures the performance of four different ways to add elements to an array: unshift
, concat
, spread
(using the rest operator), and push
. The test is designed to compare the execution speed of these methods in modern web browsers.
Options Compared
array.unshift(array2)
: This method adds all elements from array2
at the beginning of the array
.array.concat(array2)
: This method creates a new array by concatenating array
and array2
.array = [...array, ...array2]
: This is an array spread operation using the rest operator. It adds all elements from array2
to the end of array
.array.push(...array2)
: This method adds all elements from array2
at the end of the array
.Pros and Cons
unshift
: Pros: efficient for adding elements to the beginning of an array. Cons: can be slower than other methods due to the need to shift existing elements.concat
: Pros: simple and easy to understand. Cons: creates a new array, which can lead to memory allocation issues if not used carefully.spread
: Pros: concise and modern way of adding elements to an array. Cons: may be slower due to the creation of a temporary array.push
: Pros: efficient for adding elements to the end of an array. Cons: can be slower than unshift
if used with large arrays.Library Used
None in this specific benchmark, but it's worth noting that some libraries like Lodash or Ramda may provide similar functionality using different methods (e.g., lodash.array.unshift
, ramda.concat
).
Special JS Feature/Syntax
The benchmark uses the rest operator (...
) to perform the array spread operation. This feature was introduced in ECMAScript 2015 (ES6) and allows for concise way of adding elements to an array.
Other Alternatives
array.splice()
or array.insertAt()
could also be used to add elements to an array..pushStack()
method.Overall, this benchmark provides a useful comparison of different ways to add elements to an array in modern web browsers. It helps identify which methods are fastest and most efficient for specific use cases.