var params = [ "hello", true, 7 ];
var params2 = [ 1, 2 ]
var other = params2.concat(params);
var params = [ "hello", true, 7 ]
var params2 = [ 1, 2 ]
var other = [ params2, params ]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator |
Test name | Executions per second |
---|---|
Array.prototype.concat | 11253130.0 Ops/sec |
spread operator | 12689441.0 Ops/sec |
This benchmark compares two ways to combine arrays in JavaScript: the traditional Array.prototype.concat()
method and the newer spread operator (...
).
Here's a breakdown:
Array.prototype.concat()
: This method takes one or more arrays as arguments and returns a new array containing all the elements from the original arrays.
Spread Operator (...
): Introduced in ES6, this operator expands the elements of an array into individual items when used within another array literal.
In the provided test case:
[1, 2]
(params2
) with the array ["hello", true, 7]
(params
)....
) performs slightly better in this particular scenario.Alternatives:
While not directly compared here, other options exist:
push()
method: You can use the push()
method to add elements one by one to an existing array. This can be less efficient for large arrays.Let me know if you'd like to explore any of these options in more detail or have any further questions!