const a = [1,2,3,4,5,6,7,8,9,0];
const b = [1,2,3,4,5,6,7,8,9,0];
const result = a.concat(b);
const a = [1,2,3,4,5,6,7,8,9,0];
const b = [1,2,3,4,5,6,7,8,9,0];
const result = [a, b];
const a = [1,2,3,4,5,6,7,8,9,0];
const b = [1,2,3,4,5,6,7,8,9,0];
const result = [a,b].flat();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
concat | |
spread | |
flat |
Test name | Executions per second |
---|---|
concat | 4245123.5 Ops/sec |
spread | 8297798.5 Ops/sec |
flat | 243757.6 Ops/sec |
Let's break down the provided benchmarking test cases.
Benchmark Definition and Script Preparation Code
The benchmark is designed to compare three approaches for concatenating or merging arrays in JavaScript: concat
, spread
(using the spread operator), and flat
. The script preparation code is empty, which means that the baseline execution time is the default JavaScript engine's performance without any additional optimizations.
Test Cases
There are three individual test cases:
concat
: This test case uses the traditional concat()
method to merge two arrays, [1,2,3,4,5,6,7,8,9,0]
and [1,2,3,4,5,6,7,8,9,0]
.spread
: This test case uses the spread operator (...
) to merge two arrays, [1,2,3,4,5,6,7,8,9,0]
and [1,2,3,4,5,6,7,8,9,0]
. This is a modern JavaScript syntax introduced in ECMAScript 2015.flat
: This test case uses the flat()
method to merge two arrays, [1,2,3,4,5,6,7,8,9,0]
and [1,2,3,4,5,6,7,8,9,0]
. Note that this is not a standard array method in JavaScript. The flat()
method was introduced in ECMAScript 2019 as part of the Array.prototype.flat() method.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
concat
:spread
:flat
:Other Considerations
When choosing between these approaches, consider the following:
concat
might be sufficient.spread
is a good choice.flat
is the way to go.Library/External Function
None of these test cases rely on external libraries or functions. They only use built-in JavaScript methods and syntax.
Special JS Feature/Syntax
Only one special feature/syntax is used in this benchmark:
...
) introduced in ECMAScript 2015.flat()
method introduced in ECMAScript 2019.If you're not familiar with these features, don't worry! They're relatively easy to understand and use.
Alternative Benchmarks
There are alternative benchmarks available for testing array concatenation methods. Some examples include: