var arr1 = (new Array(100)).fill(0).map((x, i) => i)
var arr2 = (new Array(100)).fill(0).map((x, i) => (i + 1) * 2)
const arr = [arr1, arr2]
const arr = arr1.concat(arr2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread | |
Concat |
Test name | Executions per second |
---|---|
Spread | 102648.1 Ops/sec |
Concat | 1072887.6 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches to concatenating arrays in JavaScript: using the spread operator (...
) and using the concat()
method.
Script Preparation Code
The script preparation code generates two arrays, arr1
and arr2
, each with 100 elements. The elements are integers starting from 0 and incrementing by 1 for arr1
, and by 2 for arr2
. These arrays will be used as input to the benchmark.
Html Preparation Code
There is no HTML preparation code provided, which means that only JavaScript execution time is being measured.
Test Cases
The benchmark consists of two test cases:
...
) to concatenate arr1
and arr2
. This approach creates a new array with all elements from both input arrays.concat()
method to concatenate arr1
and arr2
. This approach returns a new array with all elements from both input arrays.Library and Purpose
Neither of the libraries mentioned in the benchmark definition are explicitly stated as being used, but it's likely that the Array.prototype.concat()
method is being compared. The purpose of this method is to concatenate two or more arrays into a single array.
Special JS Features/Syntax
The benchmark uses the spread operator (...
), which is a relatively modern JavaScript feature introduced in ECMAScript 2015 (ES6). This feature allows for concise array creation and expansion. In this benchmark, it's used to create a new array with all elements from both input arrays.
Pros and Cons of Approaches
...
):null
or undefined
is passed as an argument (although this is unlikely for arrays).concat()
):Other Alternatives
If you need to concatenate arrays in JavaScript, there are other approaches:
push()
. This approach is similar to concatenating but creates a new array instead.In summary, the benchmark compares two approaches to concatenating arrays in JavaScript: using the spread operator (...
) and using the concat()
method. The spread operator provides a concise syntax but may not work as expected with certain input types. The concat()
method is widely supported but may create intermediate objects, making it slower than the spread operator in some cases.