<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
var a = [1, 2, 3]
var b = [4, 5, 6]
var c = a.concat(b);
var c = [a, b]
var c = _.concat(a, b);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
lodash concat |
Test name | Executions per second |
---|---|
Array.prototype.concat | 2460868.5 Ops/sec |
spread operator | 3107645.8 Ops/sec |
lodash concat | 1172407.4 Ops/sec |
Let's dive into the explanation.
What is being tested?
The provided JSON represents a JavaScript microbenchmarking test that compares three approaches to concatenate two arrays: Array.prototype.concat
, the spread operator (...
), and _lodash.concat
. The test aims to measure the performance of each approach on an array of length 3, which contains values 1, 2, and 3.
Options being compared
There are three options being compared:
Array.prototype.concat"
: This is a built-in JavaScript method that concatenates two arrays and returns a new array.Spread operator (
...)
: This is a new JavaScript feature introduced in ES6 that allows you to expand an iterable (like an array) into individual elements._lodash.concat"
: This is a function from the Lodash library that concatenates two arrays and returns a new array.Library used
In this test, the Lodash library is used as a third-party dependency. _lodash.concat
is a function that concatenates two arrays and returns a new array.
Special JS feature or syntax
None of the individual test cases use special JavaScript features or syntax beyond what's required for the benchmarking itself (e.g., using var
, const
, etc.). However, it's worth noting that the spread operator (...
) is a relatively new feature introduced in ES6, which may not be supported in older browsers or environments.
Other alternatives
Some other alternatives to these approaches could include:
Array.prototype.push()
and assigning the result back to the original arrayslice()
and concatenating arrays manuallyHowever, these alternatives would likely be less efficient and more verbose than using Array.prototype.concat
, the spread operator, or _lodash.concat
.
Benchmark preparation code
The provided script preparation code creates two sample arrays a
and b
with values 1, 2, and 3. The HTML preparation code includes a link to the Lodash library.
Individual test cases
Each individual test case defines a specific benchmarking scenario using one of the three approaches:
Array.prototype.concat"
: Concatenates arrays a
and b
using concat()
.Spread operator (
...`)```: Expands arrays a
and b
into individual elements using the spread operator._lodash.concat"
: Concatenates arrays a
and b
using the _lodash.concat()
function from Lodash.These test cases are executed in a loop, allowing the benchmark to measure the performance of each approach under various conditions (e.g., multiple executions per second).