const a = [1, 2, 3];
const b = [4, 5, 6];
const c = a.concat(b);
const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [a, b];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
concat | |
spread |
Test name | Executions per second |
---|---|
concat | 7087197.5 Ops/sec |
spread | 7450744.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
What is tested on MeasureThat.net?
MeasureThat.net tests different approaches to concatenating arrays in JavaScript, specifically comparing Array.concat()
and spread syntax (...
).
Options compared:
There are two options being compared:
Array.concat()
: This method takes an array as an argument and returns a new array that contains all elements from the original array....
): This method uses the ...
operator to create a new array by spreading the elements of another array.Pros and Cons:
Array.concat()
:...
):Array.concat()
, especially for large arraysLibrary usage:
None of the test cases uses any external libraries.
Special JavaScript feature or syntax:
The ...
operator is a new feature introduced in ECMAScript 2015, also known as ES6. It allows you to create a new array by spreading elements from another array or iterable.
Other alternatives:
If Array.concat()
and spread syntax are not available or performance-critical, other alternatives for concatenating arrays include:
+
operator to concatenate arrays (e.g., [1, 2, 3] + [4, 5, 6]
)Array.prototype.push()
method to add elements to an array and then creating a new array from it (e.g., [...new Array(7).fill(null), 1, 2, 3].slice(0, 3)
)However, these alternatives are generally less efficient and less readable than using Array.concat()
or spread syntax.
Overall, the choice between Array.concat()
and spread syntax depends on the specific use case, browser support requirements, and performance considerations.