var mainArray = Array.from({ length: 10000000 }, (_, i) => i + 1)
var arrayToConcat = Array.from({ length: 10000000 }, (_, i) => Math.random() * i)
const result = mainArray.concat(arrayToConcat)
const result = [mainArray, arrayToConcat]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat() | |
Spread operator |
Test name | Executions per second |
---|---|
Array.prototype.concat() | 7.6 Ops/sec |
Spread operator | 2.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
The provided JSON represents a benchmark test case for comparing the performance of two approaches: using Array.prototype.concat()
and the spread operator (...
) to concatenate large arrays.
What are we testing?
We're testing which approach is faster when concatenating two large arrays. The test creates two arrays, one with random numbers and another with sequential numbers, each with 10 million elements. It then measures the time taken for each approach to concatenate these two arrays and report the results.
Options compared:
There are only two options being compared:
Array.prototype.concat()
: This is a built-in method in JavaScript that concatenates two or more arrays into one....
): This is a feature introduced in ES6 (ECMAScript 2015) that allows us to spread the elements of an array into another function call.Pros and cons:
Array.prototype.concat()
:...
):concat()
since it avoids the method call overhead.It's essential to note that the performance difference between these two approaches can be significant, especially when dealing with large datasets. However, for smaller arrays, the difference might be negligible.
Library:
In this benchmark test case, there is no external library being used. The code only relies on native JavaScript features.
Special JS feature or syntax:
The spread operator (...
) is a relatively new feature introduced in ES6 (ECMAScript 2015). If you're not familiar with it, think of it as a shorthand way to duplicate an array's elements into another function call. For example:
const arr = [1, 2, 3];
const doubledArr = [...arr]; // equivalent to arr.concat()
Other alternatives:
If you're interested in exploring other approaches for concatenating arrays, here are a few more options:
Array.prototype.push()
: Instead of using concat()
, you can use push()
to add elements to the end of an array and then assign it to another variable.const arr = [];
arr.push(...arrayToConcat);
reduce()
: You can also use reduce()
to concatenate arrays, although this approach might be less efficient than using concat()
.const arr = arrayToConcat.reduce((acc, current) => [...acc, current], []);
These alternatives might not offer the same performance benefits as the spread operator or concat()
, but they can still provide interesting insights into different JavaScript approaches.