<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
const params = [ { id: `2` }, { id: `3` }, { id: `4` } ];
const other = [ { id: `1` } ].concat(params);
const params = [ { id: `2` }, { id: `3` }, { id: `4` } ];
const other = _.concat([ { id: `1` } ], params);
const params = [ { id: `2` }, { id: `3` }, { id: `4` } ];
const other = [ { id: `1` }, params ];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
Lodash concat | |
Array spread |
Test name | Executions per second |
---|---|
Array.prototype.concat | 6693155.0 Ops/sec |
Lodash concat | 1930905.9 Ops/sec |
Array spread | 41807216.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The provided benchmark compares the performance of three approaches to concatenate arrays: Array.prototype.concat
, Lodash's _concat
function, and array spread operator (...
).
Test Cases
There are three test cases:
Array.prototype.concat
: This tests how fast it is to concatenate an array with another array using the concat
method._concat
function: This tests how fast it is to concatenate two arrays using Lodash's _concat
function....
): This tests how fast it is to concatenate an array with another array using the array spread operator.Options Compared
The benchmark compares the performance of these three approaches:
Array.prototype.concat
_concat
function...
)Pros and Cons
Here are some pros and cons of each approach:
Array.prototype.concat
:_concat
function:...
):Library Used
Lodash is a popular utility library that provides a set of high-order functions for functional programming. In this benchmark, Lodash's _concat
function is used to concatenate arrays.
Special JS Feature or Syntax
The array spread operator (...
) is a relatively new feature in JavaScript (introduced in ECMAScript 2018). It allows elements to be "spread" into an array or object, effectively concatenating them.
Other Alternatives
If you're looking for alternative ways to concatenate arrays, here are a few options:
Array.prototype.push
: params.push(...other)
, which can be slower than the other approaches.for (let i = 0; i < params.length; i++) { other.push(params[i]); }
, which can also be slow.However, for most use cases, the three approaches tested in this benchmark (Array.prototype.concat
, Lodash's _concat
function, and array spread operator (...
)) are likely to be sufficient.