const arr = [1, 2, 3];
const res = arr.concat(4);
const arr = [1, 2, 3];
const res = [arr, 4];
const arr = [1, 2, 3];
const res = [0, arr];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array concat | |
spread operator (appended) | |
spread operator (prepended) |
Test name | Executions per second |
---|---|
Array concat | 3920731.2 Ops/sec |
spread operator (appended) | 25489778.0 Ops/sec |
spread operator (prepended) | 28009278.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The provided JSON represents a benchmark test on MeasureThat.net, which compares three approaches to concatenate arrays in JavaScript:
concat()
method...
)These approaches are compared using three individual test cases.
Test Case 1: Array concat
const arr = [1, 2, 3];
const res = arr.concat(4);
This test case uses the traditional concat()
method to concatenate an array [1, 2, 3]
with a new element 4
. The resulting concatenated array is stored in res
.
Pros and Cons of Array concat
Test Case 2: Spread operator (appended)
const arr = [1, 2, 3];
const res = [...arr, 4];
This test case uses the spread operator (...
) to concatenate an array [1, 2, 3]
with a new element 4
. The resulting concatenated array is stored in res
.
Pros and Cons of Spread operator (appended)
concat()
due to its syntax optimizationTest Case 3: Spread operator (prepended)
const arr = [1, 2, 3];
const res = [0, ...arr];
This test case uses the spread operator (...
) to prepend an element 0
to an array [1, 2, 3]
. The resulting prepended array is stored in res
.
Pros and Cons of Spread operator (prepended)
concat()
or appending variantLibrary Used
In this benchmark, no specific JavaScript library is used. The test cases only use built-in JavaScript features.
Special JS Features/Syntax
The ES6 spread operator (...
) is a special feature introduced in ECMAScript 2015 (ES6). It allows for concise and expressive array concatenation and manipulation. However, it requires modern browser support and may not work as expected in older browsers or environments with limited JavaScript capabilities.
Other Alternatives
In addition to the traditional concat()
method and spread operator approaches, there are other ways to concatenate arrays in JavaScript:
Array.prototype.push()
: arr.push(4)
for (let i = 0; i < arr.length; i++) { arr[i] = 4 }
Array.from()
method: const res = Array.from(arr, () => 4)