const arr1 = Array.from({ length: 5000}).map((_, i) => i);
const arr2 = Array.from({ length: 5000}).map((_, i) => i);
const arr3 = Array.from({ length: 5000}).map((_, i) => i);
const finallArr1 = arr1.concat(arr2).concat(arr3);
const arr1 = Array.from({ length: 5000}).map((_, i) => i);
const arr2 = Array.from({ length: 5000}).map((_, i) => i);
const arr3 = Array.from({ length: 5000}).map((_, i) => i);
const finalArr2 = [];
arr1.forEach((e) => finalArr2.push(e));
arr2.forEach((e) => finalArr2.push(e));
arr3.forEach((e) => finalArr2.push(e));
const arr1 = Array.from({ length: 5000}).map((_, i) => i);
const arr2 = Array.from({ length: 5000}).map((_, i) => i);
const arr3 = Array.from({ length: 5000}).map((_, i) => i);
const finalArr3 = [arr1, arr2, arr3];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
concat | |
forEach | |
spread |
Test name | Executions per second |
---|---|
concat | 4438.2 Ops/sec |
forEach | 2625.2 Ops/sec |
spread | 2939.9 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Purpose
The benchmark is designed to compare the performance of three different methods for concatenating arrays:
concat()
...
)forEach()
with a callback functionOptions Compared
concat()
: uses the Array.prototype.concat()
method to concatenate two or more arrays....
): uses the spread operator to merge one or more arrays into a new array.forEach()
with a callback function: uses the Array.prototype.forEach()
method to iterate over an array and perform a specified action on each element.Pros and Cons of Each Approach
...
):Library Used
In this benchmark, no specific library is used beyond the standard JavaScript functions (e.g., Array.prototype.concat()
, Array.prototype.forEach()
).
Special JS Feature or Syntax
The benchmark uses a feature that was introduced in ECMAScript 2015 (ES6): the spread operator (...
). This feature allows you to merge arrays using a concise syntax.
Other Considerations
Array.from()
.Alternatives
Other alternatives for concatenating arrays could include:
Array.prototype.push()
to append elements to an existing array:const arr1 = [1, 2, 3];
arr1.push(4, 5, 6);
push()
or unshift()
to concatenate arrays:const arr1 = [1, 2, 3];
let finalArr = [];
for (let i = 0; i < 5000; i++) {
finalArr.push(i + 1);
}
However, these alternatives are generally less efficient and more verbose than the methods used in this benchmark.