// preparation
var a = Array.from({length: 1000}).map((_, i)=>`${i}`);
var b = Array.from({length: 2000}).map((_, i)=>`${i}`);
var aSmall = ['a', 'b', 'c', 'd'];
var bSmall = ['e', 'f', 'g', 'h', 'i'];
aSmall.concat(bSmall);
[aSmall, bSmall]
a.concat(b);
[a, b]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat small | |
spread operator (small) | |
Array.prototype.concat (large) | |
spread operator (large) |
Test name | Executions per second |
---|---|
Array.prototype.concat small | 3713005.8 Ops/sec |
spread operator (small) | 6207353.5 Ops/sec |
Array.prototype.concat (large) | 378036.7 Ops/sec |
spread operator (large) | 73231.6 Ops/sec |
Benchmark Overview
The MeasureThat.net website allows users to create and run JavaScript microbenchmarks. The provided benchmark compares the performance of two approaches for concatenating arrays: the traditional Array.prototype.concat()
method and the new ES6 spread operator (...
). The benchmark is designed to measure the execution speed of these methods on large and small datasets.
Test Cases
The benchmark consists of four test cases:
aSmall.concat(bSmall)
: This test case concatenates two small arrays, aSmall
and bSmall
, using the traditional concat()
method.[...aSmall, ...bSmall]
: This test case uses the spread operator to concatenate the same two small arrays as in the previous test case.a.concat(b)
: This test case concatenates two large arrays, a
and b
, using the traditional concat()
method.[...a, ...b]
: This test case uses the spread operator to concatenate the same two large arrays as in the previous test case.Options Compared
The benchmark compares the performance of two approaches:
Array.prototype.concat()
method...
)Pros and Cons of Each Approach
Array.prototype.concat()
method:...
):concat()
method for large arrays, as it avoids the overhead of calling a method.Library and Special JS Features
The benchmark uses no external libraries. It also does not utilize any special JavaScript features or syntax beyond what is standard in modern JavaScript (ES6 and later).
Other Alternatives
If you're looking for alternative approaches to concatenating arrays, consider the following:
Array.prototype.push()
: Instead of concatenating two arrays and then pushing elements onto one of them, use push()
to add elements to the end of an array. This can be more efficient than concatenation.Array.prototype.reduce()
or Array.prototype.forEach()
: These methods can be used to concatenate arrays by accumulating elements in a reduction function.Keep in mind that these alternatives may have different performance characteristics and use cases, so it's essential to consider the specific requirements of your project when choosing an approach.