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 ].push(params);
var params = [ "hello", true, 7 ];
var other = Array.prototype.push.apply([ 1, 2 ], params);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Push | |
Array.prototype.push.apply |
Test name | Executions per second |
---|---|
Array.prototype.concat | 7512703.5 Ops/sec |
spread operator | 7849038.5 Ops/sec |
Push | 11832251.0 Ops/sec |
Array.prototype.push.apply | 8871504.0 Ops/sec |
Let's dive into the provided benchmark JSON and explain what's being tested.
Benchmark Definition
The benchmark is designed to compare the performance of four different methods for concatenating arrays in JavaScript:
Array.prototype.concat()
...
)push()
with the spread operator (...
)Array.prototype.push.apply()
Options Compared
Each test case uses a similar input data structure, which is an array params
containing three elements: a string, a boolean, and a number.
The benchmark compares the execution time of each method for concatenating this array with another fixed-size array [1, 2]
.
Pros and Cons of Each Approach
Here's a brief analysis of each approach:
...
): Introduced in ES6, this operator allows you to spread elements from one or more arrays into another array. It's a concise way to concatenate arrays without creating a new one....
): This approach uses the spread operator to pass elements from params
to the push()
method of the target array. It's similar to using concat()
, but avoids creating a new array.concat()
.push()
method, which can be more efficient than calling push()
multiple times with individual elements.concat()
.Library and Special JS Features
None of the test cases use any libraries or special JavaScript features beyond what's built into the browser. The spread operator is a standard feature in modern JavaScript, while Array.prototype.concat()
, push()
, and Array.prototype.push.apply()
are all part of the standard library.
Considerations
When choosing an approach for concatenating arrays, consider the size and complexity of your data, as well as readability and maintainability. For small to medium-sized datasets, any of these approaches should be sufficient. However, for large or complex datasets, you may want to consider using concat()
with a more modern browser or JavaScript engine that supports its performance improvements.
Alternatives
Other alternatives for concatenating arrays include:
Set
constructor and then converting it back to an array: new Set([...params, 1, 2]).values().toArray()
reduce()
method: [...params, ...[1, 2].reduce((a, b) => [...a, b])]
However, these alternatives may not be as efficient or readable as the approaches compared in this benchmark.