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 = [[1, 2], params].flat();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Array.prototype.flat |
Test name | Executions per second |
---|---|
Array.prototype.concat | 7805219.0 Ops/sec |
spread operator | 37972360.0 Ops/sec |
Array.prototype.flat | 1075347.8 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Purpose
The benchmark is designed to compare three approaches for concatenating or flattening arrays in JavaScript:
Array.prototype.concat()
...
)Array.prototype.flat()
(specifically, when used with a single element array)Comparison of Approaches
Here's a brief overview of each approach and their pros and cons:
Array.prototype.concat()
: This method creates a new array by copying elements from two or more source arrays. It can be slower than the other two methods because it involves creating a new array object, which requires memory allocation....
): This operator creates a new array by copying elements from an existing array. It's generally faster than concat()
because it doesn't require creating a new object or allocating memory for each element.Array.prototype.flat()
: This method flattens an array by recursively concatenating sub-arrays. When used with a single-element array (like [ [1, 2] ]
), it's more efficient than concat()
or spread operator because it only requires one allocation.Library and Special JS Features
The benchmark uses JavaScript built-in functions and doesn't rely on any specific libraries. However, it does take advantage of a special syntax feature introduced in ES6: the spread operator (...
).
Test Case Explanation
Each test case is designed to measure the performance of each approach:
Array.prototype.concat()
with an array containing a string, boolean, and number....
) with the same input as the previous test case.Array.prototype.flat()
when used with a single-element sub-array.Other Alternatives
If you need to concatenate or flatten arrays in JavaScript, other alternatives include:
Array.from()
and providing an iterable source arrayArray
constructor and pushing elements from another arrayKeep in mind that these alternatives might not be as efficient or concise as the built-in functions used in the benchmark.