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 | 27110110.0 Ops/sec |
spread operator | 23603946.0 Ops/sec |
Array.prototype.flat | 17909150.0 Ops/sec |
I'll break down the benchmark and explain what's being tested, the different approaches compared, their pros and cons, and other considerations.
Benchmark Overview
The benchmark compares the performance of three ways to concatenate or manipulate arrays in JavaScript:
Array.prototype.concat()
...
)Array.prototype.flat()
(with the flat()
method)Approaches Compared
Here's a brief overview of each approach:
Array.prototype.concat()
concat()
is a traditional way to concatenate two or more arrays in JavaScript. It creates a new array and copies elements from both arrays into it.
Pros: Well-established, widely supported, easy to understand. Cons: Creates a new array, can be slower than other methods due to the overhead of creating a new object.
...
)The spread operator is a new way to concatenate arrays introduced in ES6. It allows you to use the ...
syntax to expand an array and include its elements as separate arguments.
Pros: Efficient, creates a new array with minimal overhead. Cons: Only supported in modern browsers, requires JavaScript 6+ for compatibility.
Array.prototype.flat()
flat()
is a method introduced in ES6 that flattens arrays of arrays into a single-level array. It's used here to flatten the spread operator's result.
Pros: Efficient, creates a new array with minimal overhead. Cons: Only supported in modern browsers, requires JavaScript 6+ for compatibility.
Library and Syntax
None of these approaches rely on external libraries or special JavaScript features (like async/await, Promises, etc.). However, it's worth noting that the benchmark is designed to test browser performance, which means it may not be representative of Node.js performance.
Considerations
When choosing between these approaches, consider the trade-offs:
concat()
might be sufficient....
) or flat()
.Other Alternatives
If you need even more efficiency or flexibility when working with arrays, consider these alternatives:
Array.prototype.push()
and Array.prototype.unshift()
: While not as efficient as the spread operator or flat()
, these methods can be used for array concatenation.