var array1 = Array(400).fill().map(() => Math.round(Math.random() * 40));
var array2 = Array(400).fill().map(() => Math.round(Math.random() * 40));
var others = array1.concat(array2);
var others = [array1, array2];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator |
Test name | Executions per second |
---|---|
Array.prototype.concat | 633308.0 Ops/sec |
spread operator | 35897.3 Ops/sec |
Let's break down what's happening in this benchmark.
Benchmark Description
The benchmark is comparing two ways to concatenate (merge) two arrays (array1
and array2
) with 400 elements each:
concat()
method, which is a part of JavaScript's Array prototype.[...]
) to merge the two arrays.Library
No libraries are being used in this benchmark.
Special JS Features or Syntax
[...]
), which was introduced in ECMAScript 2015 (ES6).Array(400).fill().map(() => Math.round(Math.random() * 40))
, which is a concise way to create an array of 400 elements, each containing a random number between 0 and 39.Options Compared
The two options being compared are:
concat()
method to merge the two arrays.[...]
) to merge the two arrays.Pros and Cons
Here's a brief summary of each approach:
concat()
for large arrays.Other Considerations
When deciding between these two approaches, consider the following:
Array.prototype.concat
.Other Alternatives
There are other ways to concatenate arrays in JavaScript, such as using the forEach()
method or manual looping. However, these approaches are generally less efficient than concat()
and the spread operator for large arrays.
For example:
forEach()
:var others = [];
array1.forEach(function (item) {
others.push(item);
});
array2.forEach(function (item) {
others.push(item);
});
These alternatives should be avoided unless you have specific requirements or constraints that necessitate their use.