var a = [1,2,3];
var b = [4,5,6];
b=[a,b];
b=a.concat(b);
b.unshift(a);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread | |
concat | |
unshift |
Test name | Executions per second |
---|---|
spread | 1812.3 Ops/sec |
concat | 982.0 Ops/sec |
unshift | 382566.1 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark compares the performance of three ways to join two arrays in JavaScript: using the spread operator (...
), concat()
, and unshift()
with an array.
Options Compared
...
) to create a new array by copying elements from one or more source arrays.concat()
function to concatenate two arrays, creating a new array with all elements from both arrays.unshift()
function to add an element (or multiple elements) at the beginning of an array.Pros and Cons
Library/Function Used
None of the options used a dedicated library or function. However, concat()
is a built-in JavaScript method, while unshift()
is also a native array method.
Special JS Feature/Syntax
The benchmark does not use any special JavaScript features or syntax beyond what's required for these three methods.
Other Alternatives
If you need to join arrays in other ways, some alternatives include:
reduce()
method: b = b.reduce((acc, curr) => acc.concat([curr]), [])
for
loop with an array index variablemap()
and reduce()
methods togetherKeep in mind that these alternatives may have different performance characteristics or requirements compared to the three methods being tested here.