var params = [ "hello", true, 7 ];
var otherParams = [ 1, 2 ];
var other = otherParams.concat(params);
var params = [ "hello", true, 7 ];
var otherParams = [ 1, 2 ];
var other = otherParams.push(params);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.concat() | |
Array.push( spread ) |
Test name | Executions per second |
---|---|
Array.concat() | 4954282.5 Ops/sec |
Array.push( spread ) | 24289648.0 Ops/sec |
Let's dive into the details of this benchmark.
What is being tested?
This benchmark compares two different ways to merge two arrays in JavaScript: Array.push(...)
and Array.concat()
. The goal is to measure which approach is faster.
Test Case 1: Array.concat()
In this test case, we use the concat()
method to merge two arrays:
var params = [ "hello", true, 7 ];
var otherParams = [ 1, 2 ];
var other = otherParams.concat(params);
Here, we create two separate arrays: params
and otherParams
. Then, we use the concat()
method to merge these two arrays into a new array called other
.
Test Case 2: Array.push(...)
In this test case, we use the spread operator (...
) with the push()
method to merge two arrays:
var params = [ "hello", true, 7 ];
var otherParams = [ 1, 2 ];
var other = otherParams.push(...params);
Here, we create two separate arrays: params
and otherParams
. Then, we use the spread operator (...
) to "spread" the elements of params
into a single argument for the push()
method. The push()
method then appends these elements to otherParams
, effectively merging the two arrays.
Library/Feature used:
No external libraries are used in this benchmark. However, we do use JavaScript's built-in spread operator (...
) and array methods (.concat()
and .push()
).
Pros/Cons of each approach:
concat()
in this specific scenario (as shown by the benchmark results).Other alternatives:
If you need to merge multiple arrays, you can use the concat()
method with multiple arguments:
var params = [ "hello", true, 7 ];
var otherParams1 = [ 1, 2 ];
var otherParams2 = [ 3, 4 ];
var other = [...params, ...otherParams1, ...otherParams2];
This approach uses the spread operator to merge multiple arrays into a single array. However, keep in mind that this can become cumbersome and harder to read with many arrays.
Alternatively, you can use libraries like Lodash or Underscore.js, which provide more efficient and feature-rich array manipulation functions.