var array1 = [];
var array2 = [];
var limit = 100000;
for(i = 0; i < limit; i++) {
array1.push(i);
array2.push(limit - i);
}
array1.concat(array2);
[array1, array2]
var array3 = [];
array3.push(array1);
array3.push(array2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Spread operator with push |
Test name | Executions per second |
---|---|
Array.prototype.concat | 15765.7 Ops/sec |
spread operator | 2592.7 Ops/sec |
Spread operator with push | 788.6 Ops/sec |
Let's break down the benchmark definition and test cases to understand what's being tested.
Benchmark Definition
The benchmark is designed to compare three approaches for concatenating arrays: Array.prototype.concat()
, the spread operator ([...array1, ...array2]
), and a variation of the spread operator using the push()
method (var array3 = []; array3.push(...array1); array3.push(...array2);
).
Test Cases
There are three test cases:
concat()
method to concatenate two arrays.[...array1, ...array2]
) to concatenate two arrays.push()
method to add elements to an array instead of concatenating it.Library
The benchmark uses a library called "console" which is not explicitly mentioned in the provided JSON, however console has been used throughout the script.
Special JS Feature/Syntax
None of the tests use any special JavaScript features or syntax beyond what's necessary for the comparison.
Now, let's discuss the pros and cons of each approach:
concat()
since it only creates a new array object with references to the original elements.The benchmark result shows that the spread operator with push()
is the fastest execution, followed by the spread operator, and then concat()
. This suggests that modern JavaScript engines are optimized for these new syntaxes.
Other Alternatives
If you wanted to test alternative approaches, you could consider:
Array.prototype.push.apply()
instead of push()
.concat()
with other array methods like slice()
or set()
.Keep in mind that these alternatives might not be as efficient or relevant to modern JavaScript applications, but they could provide interesting insights for certain use cases.