var array = new Array(10000).fill(1)
var toConcat = new Array(5000).fill(2)
var other = array.concat(toConcat);
var other = [ array, toConcat ]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator |
Test name | Executions per second |
---|---|
Array.prototype.concat | 147925.8 Ops/sec |
spread operator | 17280.6 Ops/sec |
Let's dive into the explanation of the provided benchmark.
What is being tested?
The benchmark compares two approaches for concatenating arrays:
Array.prototype.concat()
method...
)The test creates a large array array
with 10,000 elements filled with the value 1
, and another large array toConcat
with 5,000 elements filled with the value 2
. It then uses these arrays to concatenate them using both methods.
Options compared
The benchmark compares two options:
a. Array.prototype.concat(): This is a traditional method for concatenating arrays in JavaScript. It creates a new array and copies the elements from both input arrays into it.
b. Spread operator (...
): This is a new feature introduced in ES6 that allows you to expand an iterable (such as an array) into separate arguments to a function, or to use its elements as individual values in an expression.
Pros and Cons of each approach
a. Array.prototype.concat(): Pros:
concat()
methodCons:
b. Spread operator (...
): Pros:
concat()
Cons:
Library usage
There is no explicit library usage in this benchmark. However, it's worth noting that the spread operator relies on the Array.prototype
prototype chain, which is a built-in part of JavaScript.
Special JS feature/syntax
The benchmark uses the ES6 spread operator (...
). If you're not familiar with this feature, here's a brief explanation:
When used in an expression, the spread operator allows you to expand an iterable into separate arguments. For example:
var array = [1, 2, 3];
var other = [...array, 4, 5]; // creates a new array: [1, 2, 3, 4, 5]
In the benchmark, the spread operator is used to concatenate the toConcat
array with the array
using the syntax [ ...array, ...toConcat ]
.
Other alternatives
If you're interested in exploring alternative approaches for concatenating arrays, here are a few options:
Array.prototype.push()
and passing multiple elements: array.push(...toConcat)
Array.prototype.concat()
with an array literal: [...array].concat([...toConcat])
Keep in mind that each of these alternatives has its own trade-offs and may not be suitable for all use cases.