<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var params = [ "hello", true, 7 ];
var other = [ 1, 2 ].concat(params);
var params = [ "hello", true, 7 ]
var other = [ [1, 2], params ]
var params = [ "hello", true, 7 ];
var other = _.merge([], [1, 2], params);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Lodash merge |
Test name | Executions per second |
---|---|
Array.prototype.concat | 3217234.2 Ops/sec |
spread operator | 9709545.0 Ops/sec |
Lodash merge | 212867.8 Ops/sec |
This benchmark compares three ways to combine two arrays in JavaScript:
Array.prototype.concat()
: This is the traditional method for concatenating arrays in JavaScript. It creates a new array containing all the elements from the original arrays....
): Introduced in ES6, this operator allows you to expand an array into its individual elements. It's a more concise way to achieve the same result as concat()
._.merge()
: Lodash is a popular JavaScript library that provides utility functions for working with arrays and objects. Its _.merge()
function combines arrays (and other data structures) in a more flexible way than concat()
, considering nesting and potential deep merging.Pros and Cons:
Array.prototype.concat()
:...
):concat()
._.merge()
:Considerations:
concat()
can be slower. Lodash _.merge()
may be slower due to its additional logic.concat()
, but it might not always be obvious what it's doing in complex scenarios._.merge()
provides those options.Alternatives:
Array.from()
: This method can be used to create a new array from an iterable object (like a string or array). It's not directly comparable to concat()
, spread operator, or _.merge()
for combining existing arrays.